﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;

using System.IO;
using KD.Sms.Task;
using System.Threading;

namespace KD.Sms.UI_Operate
{
    public partial class frmSamplingCar : Form
    {
        //摄像头、光幕、激光测距参数
        private int _iVideoPort, _iVideoChannel, _iXgaPort, _iLdsPort;
        private string _strVideoIp, _strVideoUser, _strVideoUserPassWord, _strXgaIp, _strLdsIp;

        private string E_MfCom;
        private int E_MfBrandRate;
        private int E_X_Begin;
        private int E_Y_Begin;
        private int E_X_End;
        private int E_Y_End;
        private int E_Min_Space;
        private double E_xScale;
        private double E_yScale;
        private double E_xValue;
        private double E_yValue;
        private double E_zScale;
        private double E_zValue;
        private double E_zMax;

        private int E_xProtect;
        private int E_yProtect;
        private int E_xMin;
        private int E_xMax;
        private int E_yMin;
        private int E_yMax;

        /// <summary>
        /// 采样基础信息校验
        /// </summary>
        private bool _bSamplingInfoCheckOut = false;
        private int E_TieBarProtectionDistance;
        private string E_CurrentSamplingCardNo;
        private int E_CurrentSamplingIdOfLocal;
        private string E_CurrentDrawString;
        /// <summary>
        /// 车头保护值检测
        /// </summary>
        private double CarHeadProtectLength;
        /// <summary>
        /// 上一车采样批次号
        /// </summary>
        private string E_SamplingBatchLast = string.Empty;
        private string E_CarTotalLength = string.Empty, E_CarLength = string.Empty, E_CarWidth = string.Empty, E_CarHeight = string.Empty, E_CarPostion = string.Empty;
        private List<Entity.SamplingPos> E_CrrentListSamplingPos;

        /// <summary>
        /// 当前采样信息
        /// </summary>
        private Entity.SamplingInfo E_CurrentSamplingInfo { set; get; }
        private Image E_CurrentImage;

        /// <summary>
        /// 当前司机拍下按钮的流程是否在进行 
        /// </summary>
        private bool _bCapCaptureCarNo = false;

        /// <summary>
        /// 是否识别到了车牌变更
        /// </summary>
        private bool _lprIsChanged = false;

        private bool _bSaveSampleTare = false;
        private bool _bSaveSamplingImage = false;
        private bool _bSaveSendDataPacking = false;
        private bool _bSaveSendCommandPacking = false;
        private bool _bSaveSamplingComplete = false;
        public int E_SamplingPail { set; get; }
        private int E_SamplingPosCount { set; get; }
        SamplingPosMakeType E_CurrentLayoutType = SamplingPosMakeType.KD_3PartRand;
        private bool _alreadyFrameg = false;
        Entity.SamplingInfoForPailSave _modelSave;
        /// <summary>
        /// 大车移动单脉冲屋里距离 mm
        /// </summary>
        private double E_Aoto_XPulse;
        /// <summary>
        /// 小车移动单脉冲屋里距离 mm
        /// </summary>
        private double E_Aoto_YPulse;
        /// <summary>
        /// 大车相对光幕的起点脉冲
        /// </summary>
        private double E_Aoto_XBegin;
        /// <summary>
        /// 大车原点与光幕原点的距离
        /// </summary>
        private double E_Aoto_XBegin_Space;
        /// <summary>
        /// 车厢相对激光的起点
        /// </summary>
        private double E_Aoto_YBegin;
        /// <summary>
        /// 车厢相对激光的标点
        /// </summary>
        private double E_Aoto_YBeginSpace;
        /// <summary>
        /// 光幕上光点个数
        /// </summary>
        public double E_XGA_Count;
        /// <summary>
        /// 光幕上光点之间距离
        /// </summary>
        public double E_XGA_Space;
        /// <summary>
        /// 当前光栅遮挡计数
        /// </summary>
        private int E_CurtainCount { set; get; }
        /// <summary>
        /// 当前激光测距
        /// </summary>
        private double E_LaserSpace { set; get; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefresh_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 激光测距安全值
        /// </summary>
        private double E_LaserSafetyValue { set; get; }
        /// <summary>
        /// 光幕读数不到
        /// </summary>
        byte[] _byXgaNull = new byte[4];

        /// <summary>
        /// 采样机允许状态 是否暂停
        /// </summary>
        private bool E_SamplingRuning { set; get; }
        //private bool E_SamplingRuning_bak { set; get; }

        /// <summary>
        /// 采样是否准备好
        /// </summary>
        private bool E_SamplingAlready { set; get; }

        /// <summary>
        /// 采样是否完成
        /// </summary>
        private bool E_SamplingComplete { set; get; }

        /// <summary>
        /// 读取默认是否读卡状态
        /// </summary>
        private bool E_ReadCardChecked { set; get; }
        /// <summary>
        /// 司机触发采样按钮
        /// </summary>
        private bool E_NeedSamplingAotoByDriver { set; get; }

        /// <summary>
        /// 采样类型
        /// </summary>
        private SamplingType E_SamplingType { set; get; }

        /// <summary>
        /// 车号变更事件
        /// </summary>
        public event EventHandler<ActionCenter.CommonEventArgs> VehicleNumberIdentificationEvent;

        /// <summary>
        /// 当前是否自动采样（司机采样）
        /// </summary>
        private bool E_SamplingAoto { set; get; }
        /// <summary>
        /// 是否读卡器识别车号
        /// </summary>
        private bool E_SamplingCarNumByCard { set; get; }
        public frmSamplingCar()
        {
            InitializeComponent();
            E_SamplingRuning = false;
            //E_SamplingRuning_bak = true;
            E_SamplingAlready = false;
            E_SamplingComplete = false;
            E_SamplingType = SamplingType.Manual;
            E_SamplingCarNumByCard = false;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmSamplingCar_Load(object sender, EventArgs e)
        {
            if (DoLoadSysConfig())
            {
                //初始化一些界面控件
                txtPosCount.SelectedIndex = 2;
                txtLayoutType.SelectedIndex = 2;
                txtPosCount.SelectedIndex = 2;
                E_CurrentLayoutType = SamplingPosMakeType.KD_3PartRand;
                panDrawParms.Visible = CacheMemoryCenter.E_IsDebug;

                //连接摄像头
                LiveShow.DoConnect(_strVideoIp, _iVideoPort, _strVideoUser, _strVideoUserPassWord, _iVideoChannel);
                LiveShow.E_Enable = true;

                //连接光幕
                SerialServer.XGA2880RS10 _objXga = new SerialServer.XGA2880RS10(_strXgaIp, _iXgaPort);
                _objXga.ReadEvent += OnXGA_ValueRead;
                _objXga.DoRead();

                //连接激光测距
                SerialServer.LDS50 _objLds = new SerialServer.LDS50(_strLdsIp, _iLdsPort);
                _objLds.ReadEvent += OnLDS_ValueRead;
                _objLds.DoRead();

                ActionCenter.Action.Instance.CarNumChanged += OnCarNumChanged;
                Task.Cyj.Instance.PlcDataReadOut += OnPlcDataReadOut;
                VehicleNumberIdentificationEvent += OnVehicleNumberIdentificationEvent;
                CacheMemoryCenter.E_CaptureHead = null;

                cbAotoReadCard.Checked = E_ReadCardChecked;

                InitData();
                LoadData();

                //启动后台数据上传
                if (CacheSystemControl.E_ConnectSjbm)
                {
                    UI_Operate.DataUpload.DoStart();
                }
            }
            else
                UI.MsgBox.Show(UI.MsgType.Error, "程序主窗体参数加载出错！");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        Entity.CarDiscriminate _model = null;
        /// <summary>
        /// 当前读卡/车牌识别后在物流系统中获取到的车牌号
        /// </summary>
        public string E_CurrentCarNum { set; get; }

        /// <summary>
        /// 上一次在物流系统中获取到的车牌号
        /// </summary>
        public string E_CurrentCarLast { set; get; }

        /// <summary>
        ///  保存上一次 车牌识别或者刷卡获取到的 车牌号
        /// </summary>
        public string E_CurrentCardLast { set; get; }
        private void OnCarNumChanged(object sender, ActionCenter.CommonEventArgs e)
        {
            _model = (Entity.CarDiscriminate)e.E_Values;
            if (_model != null)
            {
                if (_model.E_IsError)
                    FormHelper.ApplicationShow(UI.MsgType.Waring, _model.E_CarNum);
                else
                {
                    if (E_SamplingCarNumByCard)
                    {
                        if (_model.E_Type == DiscriminateType.CardRead)
                        {
                            if (_model.E_CarNum != E_CurrentCardLast)
                            {
                                //这里得根据卡号去物流系统提车辆运输信息
                                Entity.CarTransportInfo model = DoQueryInfoFromWlSystem(_model.E_CarNum, true);
                                if (model.En_Complete)
                                {
                                    //Voicer.Instance.DoSendSound("刷卡成功!司机请下车，按，绿色，按钮启动采样。");
                                    Voicer.Instance.DoSendSound("刷卡成功!");
                                    E_CurrentCardLast = _model.E_CarNum;
                                    E_CurrentSamplingCardNo = model.En_CardNo;
                                    E_CurrentCarNum = model.En_CarLpr;
                                    //当车牌号产生异动的时候 调用物流数据
                                    if (E_CurrentCarNum != E_CurrentCarLast)
                                    {

                                        ////step3:判断是否为无人值守模拟环境，替换原有车辆信息 Test_CarInfo
                                        Entity.SamplingInfo _textModel = new Entity.SamplingInfo();
                                        if (CacheMemoryCenter.E_Unmanned)
                                        {
                                            _textModel = DAL.SqlLite.Main.Instance.GetTestCarInfo(E_CurrentCarNum);
                                            FormHelper.ApplicationShow(UI.MsgType.Information, $"车型模拟数据 整车长：{_textModel.En_TotleLength}，车厢长：{_textModel.En_Length}，整车宽：{_textModel.En_TotleWidth}，车厢宽：{_textModel.En_Width}，车底高：{_textModel.En_Height}，拉筋：{_textModel.En_Postions}");
                                            model.En_TotalLength = _textModel.En_TotleLength.ToDecimalEx();
                                            model.En_TotalWidth = _textModel.En_TotleWidth.ToDecimalEx();
                                            model.En_CLength = _textModel.En_Length.ToDecimalEx(); ;
                                            model.En_CWidth = _textModel.En_Width.ToDecimalEx();
                                            model.En_CHeight = _textModel.En_Height.ToDecimalEx();
                                            model.En_Postion = _textModel.En_Postions;
                                        }
                                        FormHelper.ApplicationShow(UI.MsgType.Information, $"车型物流数据 整车长：{model.En_TotalLength}，车厢长：{model.En_CLength}，整车宽：{model.En_TotalWidth}，车厢框：{model.En_CWidth}，车底高：{model.En_CHeight}，拉筋：{model.En_Postion}");
                                        //保存完本地
                                        if (DAL.SqlLite.Main.Instance.DoSaveDataLocal(model.En_CarLpr, model.En_CardNo, model.En_TotalLength, model.En_TotalWidth, model.En_CLength,
                                            model.En_CWidth, model.En_CHeight, model.En_Postion, model.En_Mine, model.En_Material, model.En_Supplier, model.En_Transport, model.En_Sparestr1))
                                        {
                                            FormHelper.ApplicationShow(UI.MsgType.Information, "物流信息已成功同步到本地系统");
                                        }
                                    }

                                    #region 刷卡模式下 识别到车牌自动开始采样

                                    //当前车号不为空时处理
                                    if (!string.IsNullOrEmpty(E_CurrentCarNum)
                                        && E_CurrentCarNum != E_CurrentCarLast)
                                    {
                                        //刷卡成功，播报语音
                                        Voicer.Instance.DoSendSound(string.Format("{0}车辆信息识别成功", E_CurrentCarNum));
                                        E_CurrentCarLast = E_CurrentCarNum;
                                        FormHelper.ApplicationShow(UI.MsgType.Waring, string.Format("当前车牌识别采用[{0}]模式，识别到车号[{1}]", (E_SamplingCarNumByCard ? "读卡" : "视频识别"), E_CurrentCarNum));
                                        EventHelper.DispatchEventAsync<ActionCenter.CommonEventArgs>(this, this.VehicleNumberIdentificationEvent, new ActionCenter.CommonEventArgs(E_CurrentCarNum));
                                    }

                                    #endregion

                                }
                                else
                                {
                                    Voicer.Instance.DoSendSound("刷卡失败!物流信息缺失。");
                                    E_CurrentCardLast = string.Empty;
                                }
                            }
                        }
                    }
                    else if (E_SamplingAoto)
                    {
                        if (_model.E_Type == DiscriminateType.LprCapture)
                        {
                            if (_model.E_CarNum == "无牌车")
                            {
                                FormHelper.ApplicationShow(UI.MsgType.Error, "车牌抓拍失败，识别到【无车牌】");
                                return;
                            }
                            if (_model.E_CarNum != E_CurrentCardLast)
                            {
                                //这里得根据卡号去物流系统提车辆运输信息
                                Entity.CarTransportInfo model = DoQueryInfoFromWlSystem(_model.E_CarNum, false);
                                if (model.En_Complete)
                                {
                                    //如果是无人值守模拟模式 则将本地模拟数据替换
                                    if (CacheMemoryCenter.E_Unmanned)
                                        Voicer.Instance.DoSendSound("车牌抓拍成功!司机请下车，按，绿色，按钮启动采样。");
                                    E_CurrentCardLast = _model.E_CarNum;
                                    E_CurrentSamplingCardNo = model.En_CardNo;
                                    E_CurrentCarNum = model.En_CarLpr;
                                    //当车号产生异动的时候再提取信息
                                    if (E_CurrentCarNum != E_CurrentCarLast)
                                    {

                                        ////step3:判断是否为无人值守模拟环境，替换原有车辆信息 Test_CarInfo
                                        Entity.SamplingInfo _textModel = new Entity.SamplingInfo();
                                        if (CacheMemoryCenter.E_Unmanned)
                                        {
                                            _textModel = DAL.SqlLite.Main.Instance.GetTestCarInfo(E_CurrentCarNum);
                                            FormHelper.ApplicationShow(UI.MsgType.Information, $"车型模拟数据 整车长：{_textModel.En_TotleLength}，车厢长：{_textModel.En_Length}，整车宽：{_textModel.En_TotleWidth}，车厢宽：{_textModel.En_Width}，车底高：{_textModel.En_Height}，拉筋：{_textModel.En_Postions}");
                                            model.En_TotalLength = _textModel.En_TotleLength.ToDecimalEx();
                                            model.En_TotalWidth = _textModel.En_TotleWidth.ToDecimalEx();
                                            model.En_CLength = _textModel.En_Length.ToDecimalEx(); ;
                                            model.En_CWidth = _textModel.En_Width.ToDecimalEx();
                                            model.En_CHeight = _textModel.En_Height.ToDecimalEx();
                                            model.En_Postion = _textModel.En_Postions;
                                        }
                                        FormHelper.ApplicationShow(UI.MsgType.Information, $"车型物流数据 整车长：{model.En_TotalLength}，车厢长：{model.En_CLength}，整车宽：{model.En_TotalWidth}，车厢框：{model.En_CWidth}，车底高：{model.En_CHeight}，拉筋：{model.En_Postion}");
                                        if (DAL.SqlLite.Main.Instance.DoSaveDataLocal(model.En_CarLpr, model.En_CardNo, model.En_TotalLength, model.En_TotalWidth, model.En_CLength,
                                            model.En_CWidth, model.En_CHeight, model.En_Postion, model.En_Mine, model.En_Material, model.En_Supplier, model.En_Transport, model.En_Sparestr1))
                                        {
                                            FormHelper.ApplicationShow(UI.MsgType.Information, "物流信息已成功同步到本地系统");
                                        }
                                    }

                                    #region 车牌设备模式下 不会主动触发采样，需要司机按绿色按钮

                                    //当前车号不为空时处理
                                    //if (!string.IsNullOrEmpty(E_CurrentCarNum)
                                    //    && E_CurrentCarNum != E_CurrentCarLast)
                                    //{
                                    //    //刷卡成功，播报语音
                                    //    Voicer.Instance.DoSendSound(string.Format("{0}车辆信息识别成功", E_CurrentCarNum));
                                    //    E_CurrentCarLast = E_CurrentCarNum;
                                    //    FormHelper.ApplicationShow(UI.MsgType.Waring, string.Format("当前车牌识别采用[{0}]模式，识别到车号[{1}]", (E_SamplingCarNumByCard ? "读卡" : "视频识别"), E_CurrentCarNum));
                                    //    EventHelper.DispatchEventAsync<ActionCenter.CommonEventArgs>(this, this.VehicleNumberIdentificationEvent, new ActionCenter.CommonEventArgs(E_CurrentCarNum));
                                    //}

                                    #endregion
                                }
                                else
                                {
                                    Voicer.Instance.DoSendSound("车牌抓拍失败!物流信息缺失。");
                                    E_CurrentCardLast = string.Empty;
                                }
                            }
                        }
                    }
                    else
                    {
                        //FormHelper.ApplicationShow(UI.MsgType.Information, "");
                    }
                    //当前车号不为空时处理
                    //if (!string.IsNullOrEmpty(E_CurrentCarNum)
                    //    && E_CurrentCarNum != E_CurrentCarLast)
                    //{
                    //    //刷卡成功，
                    //    //Voicer.Instance.DoSendSound("刷卡成功!");
                    //    Voicer.Instance.DoSendSound(string.Format("{0}车辆信息识别成功，司机请下车，按，绿色，按钮启动采样。", E_CurrentCarNum));
                    //    //E_CurrentCarLast = E_CurrentCarNum;
                    //    FormHelper.ApplicationShow(UI.MsgType.Waring, string.Format("当前车牌识别采用[{0}]模式，识别到车号[{1}]", (E_SamplingCarNumByCard ? "读卡" : "视频识别"), E_CurrentCarNum));
                    //}
                }
            }
            else
                FormHelper.ApplicationShow(UI.MsgType.Waring, "车牌号识别有误");
        }

        /// <summary>
        /// 根据卡号或者车牌号提取物流信息
        /// </summary>
        /// <param name="cardno"></param>
        /// <param name="isCard"></param>
        /// <returns></returns>
        decimal _dTotalLength, _dTotalWidth, _dLength, _dWidth, _dHeight;
        string _strMine, _strSupplier, _strMateral, _strTransport, _strPostion, _strCarno, _strCardNo, _strSparestr1;
        DataTable _tabTransportSources = null;
        private Entity.CarTransportInfo DoQueryInfoFromWlSystem(string cardno, bool isCard)
        {
            Entity.CarTransportInfo model = new Entity.CarTransportInfo();
            try
            {
                _tabTransportSources = DAL.Sqlserver.Interface.Instance.DoQueryCarNumByCarNumOrCard(cardno, isCard);
                if (_tabTransportSources != null)
                {
                    if (_tabTransportSources.Rows.Count == 1)
                    {
                        decimal.TryParse(_tabTransportSources.Rows[0]["totallength"].ToString(), out _dTotalLength);
                        decimal.TryParse(_tabTransportSources.Rows[0]["totalwidth"].ToString(), out _dTotalWidth);
                        decimal.TryParse(_tabTransportSources.Rows[0]["clength"].ToString(), out _dLength);
                        decimal.TryParse(_tabTransportSources.Rows[0]["cwidth"].ToString(), out _dWidth);
                        decimal.TryParse(_tabTransportSources.Rows[0]["cheight"].ToString(), out _dHeight);
                        _strCarno = _tabTransportSources.Rows[0]["carno"].ToString();
                        _strMine = _tabTransportSources.Rows[0]["kind"].ToString();
                        _strMateral = _tabTransportSources.Rows[0]["material"].ToString();
                        _strSupplier = _tabTransportSources.Rows[0]["supplier"].ToString();
                        _strTransport = _tabTransportSources.Rows[0]["transport"].ToString();
                        _strPostion = _tabTransportSources.Rows[0]["cpostion"].ToString();
                        _strCardNo = _tabTransportSources.Rows[0]["cardno"].ToString();
                        //吴幽 获取车辆流程号，上传至三级编码中保存 sparestr1
                        _strSparestr1 = _tabTransportSources.Rows[0]["sparestr1"].ToString();
                        //赋值
                        model.En_CardNo = cardno;
                        model.En_CarLpr = _strCarno;
                        model.En_TotalLength = _dTotalLength;
                        model.En_TotalWidth = _dTotalWidth;
                        model.En_CLength = _dLength;
                        model.En_CWidth = _dWidth;
                        model.En_CHeight = _dHeight;
                        model.En_Postion = _strPostion;
                        model.En_Mine = _strMine;
                        model.En_Material = _strMateral;
                        model.En_Supplier = _strSupplier;
                        model.En_Transport = _strTransport;
                        model.En_CardNo = _strCardNo;
                        model.En_Sparestr1 = _strSparestr1;

                        FormHelper.ApplicationShow(UI.MsgType.Information, "从物流系统提取信息如下:");
                        FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("卡号:{0}", _strCardNo));
                        FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("车号:{0}", _strCarno));
                        FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("流程号:{0}", _strSparestr1));
                        #region 根据权限设置隐藏 供应商关键信息
                        FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("品名:{0}", CacheUser.E_KeyInformation ? _strMine : "*****"));
                        FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("物料:{0}", CacheUser.E_KeyInformation ? _strMateral : "*********"));
                        FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("供应商:{0}", CacheUser.E_KeyInformation ? _strSupplier : "*************"));
                        FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("运输商:{0}", CacheUser.E_KeyInformation ? _strTransport : "*************"));
                        #endregion
                        FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("整车长:{0} 整车宽:{1} 车厢长:{2} 车厢宽:{3} 车厢离地高:{4}", _dTotalLength, _dTotalWidth, _dLength, _dWidth, _dHeight));
                        //FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("整车宽:{0}", _dTotalWidth));
                        //FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("车厢长:{0}", _dLength));
                        //FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("车厢宽:{0}", _dWidth));
                        //FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("车厢离地高:{0}", _dHeight));
                        FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("拉筋位置:{0}", _strPostion));
                        model.En_Complete = true;
                    }
                    else
                    {
                        FormHelper.ApplicationShow(UI.MsgType.Error, string.Format("根据卡号【{0}】从物流系统提取到多条数据，系统无法自动判断", cardno));
                    }
                }
                else
                    FormHelper.ApplicationShow(UI.MsgType.Error, "从物流系统获取车辆物流信息失败.");
            }
            catch (Exception ex)
            {
                FormHelper.ApplicationShow(UI.MsgType.Error, "从物流系统获取车辆物流信息出现未知异常.");
                Log.LogHelper.DoWriteLogTypeSubitem(Log.LogType.Error, Log.LogSubitem.System, "从物流系统获取车辆物流信息出现未知异常！");
                Log.LogHelper.DoWriteLogTypeSubitem(Log.LogType.Error, Log.LogSubitem.System, ex.ToString());
            }
            return model;
        }

        /// <summary>
        /// 识别到车号之后做相关处理
        /// </summary>
        /// <param name="send"></param>
        /// <param name="e"></param>
        private void OnVehicleNumberIdentificationEvent(object send, ActionCenter.CommonEventArgs e)
        {
            if (E_SamplingAlready)
            {
                UI.FormHelper.SetComboxTextForFind(txtProvince, E_CurrentCarNum.Substring(0, 1));
                UI.FormHelper.SetControlText(txtCarno, E_CurrentCarNum.Substring(1, E_CurrentCarNum.Length - 1));
                DoExtractDataFromSystem(true);
            }
            else
            {
                _bCapCaptureCarNo = false;//解除司机按钮防误触锁定
                FormHelper.ApplicationShow(UI.MsgType.Information, $"采样没有准备好");
            }

            //if (E_SamplingAlready)
            //{
            //    //无人值守 是否测试模式 不执行采样流程
            //    if ( CacheMemoryCenter.E_NoSampling)
            //    {
            //        UI.FormHelper.SetComboxTextForFind(txtProvince, E_CurrentCarNum.Substring(0, 1));
            //        UI.FormHelper.SetControlText(txtCarno, E_CurrentCarNum.Substring(1, E_CurrentCarNum.Length - 1));
            //        DoExtractDataFromSystem(true);
            //    }
            //    else
            //        FormHelper.ApplicationShow(UI.MsgType.Information, $"司机触发采样：测试模式，触发模拟采样...");
            //}
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="isRuning"></param>
        private void DoSetButtonPauseStyle(bool isRuning)
        {
            if (isRuning)
            {
                UI.FormHelper.SetControlText(btnPause, "暂停运行");
                UI.FormHelper.SetControlBackColor(btnPause, Color.Teal);
            }
            else
            {
                UI.FormHelper.SetControlText(btnPause, "恢复运行");
                UI.FormHelper.SetControlBackColor(btnPause, Color.Goldenrod);
            }
        }

        /// <summary>
        /// 设置半自动按钮样式
        /// </summary>
        /// <param name="isHalfAuto"></param>
        private void DoSetHalfAutoButtonStyle(bool isHalfAutoReady)
        {
            if (isHalfAutoReady)
            {
                UI.FormHelper.SetControlBackColor(btnBigBack, Color.Teal);
                UI.FormHelper.SetControlBackColor(btnBigForward, Color.Teal);
                UI.FormHelper.SetControlBackColor(btnSmallLeft, Color.Teal);
                UI.FormHelper.SetControlBackColor(btnSmallRight, Color.Teal);
            }
            else
            {
                UI.FormHelper.SetControlBackColor(btnBigBack, Color.Gray);
                UI.FormHelper.SetControlBackColor(btnBigForward, Color.Gray);
                UI.FormHelper.SetControlBackColor(btnSmallLeft, Color.Gray);
                UI.FormHelper.SetControlBackColor(btnSmallRight, Color.Gray);
            }
            UI.FormHelper.SetControlEnabled(btnBigBack, isHalfAutoReady);
            UI.FormHelper.SetControlEnabled(btnBigForward, isHalfAutoReady);
            UI.FormHelper.SetControlEnabled(btnSmallLeft, isHalfAutoReady);
            UI.FormHelper.SetControlEnabled(btnSmallRight, isHalfAutoReady);
        }

        /// <summary>
        /// 设置自动采样按钮模式
        /// </summary>
        /// <param name="isHalfAuto"></param>
        private void DoSetAutoButtonStyle(bool isAotoReady)
        {
            if (CacheSystemControl.E_SamplingSerialjob)
            {
                UI.FormHelper.SetControlEnabled(btnAoto, (isAotoReady && CacheSamplingPacking.E_PackingObjectsCount <= 1));
                UI.FormHelper.SetControlBackColor(btnAoto, (isAotoReady && CacheSamplingPacking.E_PackingObjectsCount <= 1) ? Color.Teal : Color.Gray);
            }
            else
            {
                UI.FormHelper.SetControlEnabled(btnAoto, (isAotoReady && CacheSamplingPacking.E_PackingObjectsCount == 0));
                UI.FormHelper.SetControlBackColor(btnAoto, (isAotoReady && CacheSamplingPacking.E_PackingObjectsCount == 0) ? Color.Teal : Color.Gray);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private bool DoLoadSysConfig()
        {
            try
            {
                //视频通讯参数
                _strVideoIp = ConfigurationManager.AppSettings["VideoIp"].ToString();
                _strVideoUser = ConfigurationManager.AppSettings["VideoUser"].ToString();
                _strVideoUserPassWord = ConfigurationManager.AppSettings["VideoUserPassWord"].ToString();
                _iVideoPort = int.Parse(ConfigurationManager.AppSettings["VideoPort"].ToString());
                _iVideoChannel = int.Parse(ConfigurationManager.AppSettings["VideoChannel"].ToString());
                E_xScale = double.Parse(ConfigurationManager.AppSettings["X_Scale"].ToString());
                E_xValue = double.Parse(ConfigurationManager.AppSettings["X_Const"].ToString());
                E_yScale = double.Parse(ConfigurationManager.AppSettings["Y_Scale"].ToString());
                E_yValue = double.Parse(ConfigurationManager.AppSettings["Y_Const"].ToString());
                E_zScale = double.Parse(ConfigurationManager.AppSettings["Z_Scale"].ToString());
                E_zValue = double.Parse(ConfigurationManager.AppSettings["Z_Const"].ToString());
                E_zMax = double.Parse(ConfigurationManager.AppSettings["Z_Max"].ToString());

                E_Min_Space = int.Parse(ConfigurationManager.AppSettings["Min_Space"].ToString());
                E_xProtect = int.Parse(ConfigurationManager.AppSettings["XProct"].ToString());
                E_yProtect = int.Parse(ConfigurationManager.AppSettings["YProct"].ToString());
                E_xMin = int.Parse(ConfigurationManager.AppSettings["X_RunMin"].ToString());
                E_xMax = int.Parse(ConfigurationManager.AppSettings["X_RunMax"].ToString());
                E_yMin = int.Parse(ConfigurationManager.AppSettings["Y_RunMIn"].ToString());
                E_TieBarProtectionDistance = int.Parse(ConfigurationManager.AppSettings["BraceDistanceProtec"].ToString());
                E_yMax = int.Parse(ConfigurationManager.AppSettings["Y_RunMax"].ToString());
                E_Aoto_XPulse = double.Parse(ConfigurationManager.AppSettings["Aoto_XPulse"].ToString());
                E_Aoto_YPulse = double.Parse(ConfigurationManager.AppSettings["Aoto_YPulse"].ToString());
                E_Aoto_XBegin = double.Parse(ConfigurationManager.AppSettings["Aoto_XBegin"].ToString());
                E_Aoto_XBegin_Space = double.Parse(ConfigurationManager.AppSettings["Aoto_XbeginSpace"].ToString());
                E_Aoto_YBegin = double.Parse(ConfigurationManager.AppSettings["Aoto_YBegin"].ToString());
                E_Aoto_YBeginSpace = double.Parse(ConfigurationManager.AppSettings["Aoto_YBeginSpace"].ToString());
                E_XGA_Count = double.Parse(ConfigurationManager.AppSettings["XGA_Count"].ToString());
                E_XGA_Space = double.Parse(ConfigurationManager.AppSettings["XGA_Space"].ToString());
                CarHeadProtectLength = ConfigurationManager.AppSettings["CarHeadLength"].ToDoubleEx() <= 0 ? 3.5 : CarHeadProtectLength;

                //读卡器参数
                E_MfCom = ConfigurationManager.AppSettings["MF_Com"].ToString();
                E_MfBrandRate = int.Parse(ConfigurationManager.AppSettings["MF_BrandRate"].ToString());

                E_ReadCardChecked = Convert.ToBoolean(int.Parse(ConfigurationManager.AppSettings["ReadCardChecked"].ToString()));

                //光幕通讯参数
                _byXgaNull[0] = 0x00;
                _byXgaNull[1] = 0x00;
                _byXgaNull[2] = 0x00;
                _byXgaNull[3] = 0x00;
                _strXgaIp = ConfigurationManager.AppSettings["XGA_Ip"].ToString();
                _iXgaPort = int.Parse(ConfigurationManager.AppSettings["XGA_Port"].ToString());

                //激光测距参数
                _strLdsIp = ConfigurationManager.AppSettings["LDS_Ip"].ToString();
                _iLdsPort = int.Parse(ConfigurationManager.AppSettings["LDS_Port"].ToString());
                E_LaserSafetyValue = double.Parse(ConfigurationManager.AppSettings["LaserSpace"].ToString());
                return true;
            }
            catch (Exception ex)
            {
                Log.LogHelper.DoWriteLogTypeSubitem(Log.LogType.Error, Log.LogSubitem.System, "程序主窗体参数加载出错！");
                Log.LogHelper.DoWriteLogTypeSubitem(Log.LogType.Error, Log.LogSubitem.System, ex.ToString());
                return false;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="send"></param>
        /// <param name="e"></param>
        private void OnXGA_ValueRead(object send, SerialServer.CommonEventArgs e)
        {
            if (e.M_Value == 9999)
            {
                FormHelper.ApplicationShow(UI.MsgType.Error, "红外光幕网络中断");
                return;
            }
            if (string.IsNullOrEmpty(e.M_Error))
            {
                if (e.M_Buffer != null)
                {
                    Curtain.E_Values = e.M_Buffer;
                    E_CurtainCount = Curtain.E_CarPostion;
                    CacheMemoryCenter.M_CurtainCount = E_CurtainCount;
                    UI.FormHelper.SetControlText(txtLightCurtain, E_CurtainCount.ToString());
                }
            }
            else
            {
                E_CurtainCount = 0;
                CacheMemoryCenter.M_CurtainCount = 0;
                FormHelper.ApplicationShow(UI.MsgType.Error, e.M_Error);
                Curtain.E_Values = _byXgaNull;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="send"></param>
        /// <param name="e"></param>
        private void OnLDS_ValueRead(object send, SerialServer.CommonEventArgs e)
        {
            if (e.M_Value == 9999)
            {
                FormHelper.ApplicationShow(UI.MsgType.Error, "激光测距仪网络中断");
                return;
            }
            if (!string.IsNullOrEmpty(e.M_Error))
            {
                FormHelper.ApplicationShow(UI.MsgType.Error, e.M_Error);
                UI.FormHelper.SetControlText(txtLaserSapce, "0");
                E_LaserSpace = 0;
                CacheMemoryCenter.M_LaserSpace = 0;
            }
            else
            {
                UI.FormHelper.SetControlText(txtLaserSapce, e.M_Value.ToString("F4"));
                E_LaserSpace = Convert.ToDouble(e.M_Value);
                CacheMemoryCenter.M_LaserSpace = E_LaserSpace;
            }
        }
        #region 按钮操作
        private void btnBigForward_MouseDown(object sender, MouseEventArgs e)
        {
            Task.Cyj.Instance.DoWrite(0, 301);
        }

        private void btnBigBack_MouseDown(object sender, MouseEventArgs e)
        {
            Task.Cyj.Instance.DoWrite(0, 302);
        }

        private void btnSmallLeft_MouseDown(object sender, MouseEventArgs e)
        {
            Task.Cyj.Instance.DoWrite(0, 303);
        }

        private void btnSmallRight_MouseDown(object sender, MouseEventArgs e)
        {
            Task.Cyj.Instance.DoWrite(0, 304);
        }

        private void btnBigForward_MouseUp(object sender, MouseEventArgs e)
        {
            Task.Cyj.Instance.DoWrite(0, 0);
        }

        private void btnBigBack_MouseUp(object sender, MouseEventArgs e)
        {
            Task.Cyj.Instance.DoWrite(0, 0);
        }

        private void btnSmallLeft_MouseUp(object sender, MouseEventArgs e)
        {
            Task.Cyj.Instance.DoWrite(0, 0);
        }

        private void btnSmallRight_MouseUp(object sender, MouseEventArgs e)
        {
            Task.Cyj.Instance.DoWrite(0, 0);
        }

        private void btnResetDevice_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否确定复位当前设备动作流程?", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                DAL.SqlLite.Main.Instance.LogWrite(SysLogType.Login, "点击设备复位");

                Task.Cyj.Instance.DoWrite(0, 200);
                E_NeedSamplingAotoByDriver = false;
            }
        }

        private void btnResetError_Click(object sender, EventArgs e)
        {
            Task.Cyj.Instance.DoWrite(0, 700);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtTotalLength_TextChanged(object sender, EventArgs e)
        {
            E_CarTotalLength = txtTotalLength.Text.Trim();
        }

        private void txtWidth_TextChanged(object sender, EventArgs e)
        {
            E_CarWidth = txtWidth.Text.Trim();
        }

        private void txtLength_TextChanged(object sender, EventArgs e)
        {
            E_CarLength = txtLength.Text.Trim();
        }

        private void txtPostions_TextChanged(object sender, EventArgs e)
        {
            E_CarPostion = txtPostions.Text.Trim();
        }

        private void txtHeight_TextChanged(object sender, EventArgs e)
        {
        }

        private void txtHeight_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (E_SamplingAlready && E_CrrentListSamplingPos != null && E_CrrentListSamplingPos.Count > 0)
            {
                FormHelper.ApplicationShow(UI.MsgType.Error, "高度发生变化，需要重新画框!");
                E_CrrentListSamplingPos = null;
            }
            E_CarHeight = txtHeight.Text.Trim();
        }

        private void btnPause_Click(object sender, EventArgs e)
        {
            if (btnPause.Text.IndexOf("暂停") >= 0)
                Task.Cyj.Instance.DoWrite(150, 100);
            else
                Task.Cyj.Instance.DoWrite(150, 0);

            DAL.SqlLite.Main.Instance.LogWrite(SysLogType.Login, string.Format("点击设备{0}", btnPause.Text.IndexOf("暂停") >= 0 ? "暂停" : "恢复"));
        }
        #endregion

        /// <summary>
        /// 自动开始采样
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAoto_Click(object sender, EventArgs e)
        {
            //如果是测试模式
            if (_bIsTest)
            {
                btnQzAoto_Click(sender, e);
                return;
            }

            if (CacheUser.E_LockSampling)
            {
                UI.MsgBox.Show(UI.MsgType.Error, "管理员禁止采样!");
                return;
            }
            DoJudgeWaste();

            if (CacheSamplingPacking.E_PackingObjectsCount > 1)
            {
                UI.MsgBox.Show(UI.MsgType.Error, "当前封装机封装煤样超过一份，系统判断封装机出现故障，建议人工介入处理后重启采样系统!");
                return;
            }
            if (!_alreadyFrameg)
            {
                UI.MsgBox.Show(UI.MsgType.Error, "画框采样请先画框");
                return;
            }

            if (E_CrrentListSamplingPos == null || E_CrrentListSamplingPos.Count < 1)
            {
                UI.MsgBox.Show(UI.MsgType.Error, "尚未生成布点方案，无法开始采样");
                return;
            }

            if (E_CrrentListSamplingPos.Count != E_SamplingPosCount)
            {
                UI.MsgBox.Show(UI.MsgType.Error, "生成采样点数与选择采样点数不符，建议重新选择采样点后画框!");
                return;
            }

            if (E_CurrentSamplingInfo == null)
            {
                UI.MsgBox.Show(UI.MsgType.Error, "采样信息不完整，无法开始采样");
                return;
            }
            //根据批次号提取合适的样桶
            decimal _dSampleWeightHistory = DAL.SqlLite.Main.Instance.DoGetSampleWeight(E_CurrentSamplingInfo.En_Materiel, E_CurrentSamplingInfo.En_Supplier);
            FormHelper.ApplicationShow(UI.MsgType.Error, string.Format("获取到同物料同供应商的历史平均采样量{0}kg", _dSampleWeightHistory));
            E_SamplingPail = DAL.SqlLite.Main.Instance.DoGetPailForSampling(E_CurrentSamplingInfo.En_Batch, E_CurrentSamplingInfo.En_SamplingPosCount, CacheSamplingPacking.DoGetCachePointCount(), _dSampleWeightHistory);
            if (E_SamplingPail <= 0)
            {
                /*当前样桶已满，需要出桶*/
                UI.MsgBox.Show(UI.MsgType.Error, "已无样桶可用于当前采样");
                return;
            }
            else
            {
                E_CurrentSamplingInfo.En_SamplingPail = E_SamplingPail;
                UI.FormHelper.SetComboxTextForFind(txtPail, E_SamplingPail.ToString());
            }

            //启用记忆缩分功能
            int _iSubdivision = 0;
            if (CacheSystemControl.E_MemoryReductionc)
            {
                _iSubdivision = DAL.SqlLite.Main.Instance.DoQuerySubdivisionForSamplings(E_CurrentSamplingInfo.En_Materiel, E_CurrentSamplingInfo.En_Supplier);
                if (_iSubdivision <= 0)
                    _iSubdivision = CacheSystemControl.E_ReductioncDefaultSet;
                if (_iSubdivision != CacheSystemControl.E_ReductioncCurrent)
                {
                    if (Task.Cyj.Instance.DoWrite(154, (short)_iSubdivision))
                    {
                        FormHelper.ApplicationShow(UI.MsgType.Waring, string.Format("系统当前启用记忆缩分功能，缩分间隔{0}设定成功", _iSubdivision));
                        System.Threading.Thread.Sleep(300);
                    }
                    else
                        FormHelper.ApplicationShow(UI.MsgType.Error, string.Format("系统当前启用记忆缩分功能，缩分间隔{0}设定失败", _iSubdivision));
                }
            }

            double _dTotalLength, _dCLength, _dCwidth, _dCheight;
            double.TryParse(E_CarTotalLength, out _dTotalLength);
            double.TryParse(E_CarLength, out _dCLength);
            double.TryParse(E_CarWidth, out _dCwidth);
            double.TryParse(E_CarHeight, out _dCheight);
            E_CurrentSamplingInfo.En_TotleLength = _dTotalLength;
            E_CurrentSamplingInfo.En_Length = _dCLength;
            E_CurrentSamplingInfo.En_Width = _dCwidth;
            E_CurrentSamplingInfo.En_Height = _dCheight;
            E_CurrentSamplingInfo.En_Postions = txtPostions.Text == "0" ? string.Empty : txtPostions.Text;

            if (DAL.SqlLite.Main.Instance.DoInsertSamplingBegin(E_CurrentSamplingInfo, E_CrrentListSamplingPos, out E_CurrentSamplingIdOfLocal))
            {

                //生成采样标签
                E_CurrentDrawString = string.Format("车牌号：{0}\r\n批次号：{1}\r\n煤种：{2}\r\n物料：{3}\r\n供应商：{4}\r\n采样点数：{5}\r\n布点方式：{6}\r\n缩分间隔：{13}\r\n布点坐标：{7}\r\n车长：{8}m\r\n车厢长：{9}m\r\n车厢宽：{10}m\r\n车厢离地高：{11}\r\n拉筋位置：{12}",
                                                    E_CurrentSamplingInfo.En_Car, E_CurrentSamplingInfo.En_Batch, CacheUser.E_KeyInformation ? E_CurrentSamplingInfo.En_MineName : "", CacheUser.E_KeyInformation ? E_CurrentSamplingInfo.En_MaterielName : "",
                                                    CacheUser.E_KeyInformation ? E_CurrentSamplingInfo.En_SupplierName : "", E_CrrentListSamplingPos.Count, EnumHelper.GetEnumDes(E_CurrentLayoutType), DoGetPosintString(E_CrrentListSamplingPos),
                                                    E_CarTotalLength, E_CarLength, E_CarWidth, E_CarHeight, E_CarPostion, _iSubdivision);

                //保存车头照片
                if (CacheMemoryCenter.E_CaptureHead != null)
                {
                    Image _imgBegin = DoDrawString(CacheMemoryCenter.E_CaptureHead, E_CurrentDrawString, Color.Yellow, 10);
                    MemoryStream memoryStream = new MemoryStream();
                    _imgBegin.Save(memoryStream, ImageFormat.Jpeg);
                    var imgPath = ImageSaver.DoSaveImage(E_CurrentSamplingIdOfLocal, _imgBegin, true);
                    if (DAL.SqlLite.Main.Instance.DoInsertImages(imgPath, true, E_CurrentSamplingIdOfLocal))
                        FormHelper.ApplicationShow(UI.MsgType.Information, "开始采样图片本地保存成功");
                    else
                        FormHelper.ApplicationShow(UI.MsgType.Error, "开始采样图片本地保存出错!详见日志");
                    memoryStream = null;
                }
                FormHelper.ApplicationShow(UI.MsgType.Information, "采样开始数据本地保存成功");
                short[] _CmdPlcs = new short[E_CrrentListSamplingPos.Count * 3 + 14];
                bool _bNeedClear = E_CurrentSamplingInfo.En_Batch != E_SamplingBatchLast;
                if (_bNeedClear)
                    FormHelper.ApplicationShow(UI.MsgType.Error, "采样批次产生变更，当前需要清洗");
                _CmdPlcs[0] = _bNeedClear ? (short)101 : (short)100;//100正常采样 101清洗采样
                _CmdPlcs[1] = (short)E_CurrentSamplingInfo.En_SamplingPosCount;
                _CmdPlcs[2] = (short)E_CurrentSamplingInfo.En_SamplingPail;
                for (int i = 3; i < 14; i++)
                {
                    _CmdPlcs[i] = 0;
                }
                int _iStep = 14;
                foreach (Entity.SamplingPos pos in E_CrrentListSamplingPos)
                {
                    _CmdPlcs[_iStep] = (short)pos.X;
                    _iStep++;
                    _CmdPlcs[_iStep] = (short)pos.Y;
                    _iStep++;
                    _CmdPlcs[_iStep] = (short)pos.Z;
                    _iStep++;
                }

                //开始采样
                if (Task.Cyj.Instance.DoWrite(0, _CmdPlcs))
                {
                    FormHelper.ApplicationShow(UI.MsgType.Information, "开始采样命令下达成功");
                    E_CrrentListSamplingPos = null;
                    CacheMemoryCenter.E_SamplingInfo = E_CurrentSamplingInfo;

                    //将采样信息打包,采样完成之后传入封装机使用
                    _bSaveSendDataPacking = false;
                    _modelSave = new Entity.SamplingInfoForPailSave();
                    _modelSave.E_SamplingCarNum = E_CurrentCarNum;
                    _modelSave.E_SamplingIdIfLocal = E_CurrentSamplingIdOfLocal;
                    _modelSave.E_SamplingPail = E_CurrentSamplingInfo.En_SamplingPail;
                    _modelSave.E_SamplingPoscount = E_CurrentSamplingInfo.En_SamplingPosCount;
                    _modelSave.E_SamplingPailCard = string.Empty;
                    _modelSave.E_SamplingBatchCode = E_CurrentSamplingInfo.En_Batch;
                    //记录上一车的批次号
                    E_SamplingBatchLast = E_CurrentSamplingInfo.En_Batch;
                    E_CurrentSamplingInfo = null;
                    _bSaveSamplingImage = false;
                    _bSaveSamplingComplete = false;

                    LiveShow.DoClearScreen();
                    CacheMemoryCenter.E_CaptureHead = null;
                    ActionCenter.Action.Instance.DoRefreshSamplingPail();
                    //语音播报
                    Voicer.Instance.DoSendSound("采样开始，请站在安全区域等待");
                }
                else
                    FormHelper.ApplicationShow(UI.MsgType.Error, "开始采样命令下达失败!详见日志");
            }
            else
                FormHelper.ApplicationShow(UI.MsgType.Error, "采样开始数据本地保存失败");
        }

        /// <summary>
        /// 强制采样调试测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQzAoto_Click(object sender, EventArgs e)
        {
            if (CacheUser.E_LockSampling)
            {
                UI.MsgBox.Show(UI.MsgType.Error, "管理员禁止采样!");
                return;
            }
            DoJudgeWaste();

            if (!_alreadyFrameg)
            {
                UI.MsgBox.Show(UI.MsgType.Error, "请先画框");
                return;
            }

            if (E_CrrentListSamplingPos == null || E_CrrentListSamplingPos.Count < 1)
            {
                UI.MsgBox.Show(UI.MsgType.Error, "尚未生成布点方案，无法开始采样");
                return;
            }

            if (E_CrrentListSamplingPos.Count != E_SamplingPosCount)
            {
                UI.MsgBox.Show(UI.MsgType.Error, "生成采样点数与选择采样点数不符，建议重新选择采样点后画框!");
                return;
            }

            if (1 == 1)
            {
                short[] _CmdPlcs = new short[E_CrrentListSamplingPos.Count * 3 + 14];

                _CmdPlcs[0] = 100;//100正常采样
                _CmdPlcs[1] = (short)(txtPosCount.Text.ToIntEx() <= 0 ? 3 : txtPosCount.Text.ToIntEx());//采样点数
                _CmdPlcs[2] = 1;//采样桶号
                for (int i = 3; i < 14; i++)
                {
                    _CmdPlcs[i] = 0;
                }
                int _iStep = 14;
                foreach (Entity.SamplingPos pos in E_CrrentListSamplingPos)
                {
                    _CmdPlcs[_iStep] = (short)pos.X;
                    _iStep++;
                    _CmdPlcs[_iStep] = (short)pos.Y;
                    _iStep++;
                    _CmdPlcs[_iStep] = (short)pos.Z;
                    _iStep++;
                }

                //开始采样
                if (Task.Cyj.Instance.DoWrite(0, _CmdPlcs))
                {
                    FormHelper.ApplicationShow(UI.MsgType.Information, "测试采样命令下达成功");
                    E_CrrentListSamplingPos = null;
                    E_CurrentSamplingInfo = null;
                    _bSaveSamplingImage = false;
                    _bSaveSamplingComplete = false;
                    LiveShow.DoClearScreen();
                    CacheMemoryCenter.E_CaptureHead = null;
                    ActionCenter.Action.Instance.DoRefreshSamplingPail();
                    //语音播报
                    Voicer.Instance.DoSendSound("采样开始，请站在安全区域等待");
                }
                else
                    FormHelper.ApplicationShow(UI.MsgType.Error, "开始采样命令下达失败!详见日志");
            }
            else
                FormHelper.ApplicationShow(UI.MsgType.Error, "采样开始数据本地保存失败");
        }


        /// <summary>
        /// 判断当前是否需要弃料
        /// </summary>
        /// <returns></returns>
        System.Data.DataTable _tabWaste;
        int _iWasteSet = 0, _iWasteCurrent = 0;

        private void cbSerialJob_CheckedChanged(object sender, EventArgs e)
        {
            CacheSystemControl.E_SamplingSerialjob = cbSerialJob.Checked;
            FormHelper.ApplicationShow(UI.MsgType.Error, string.Format("设定当前{0}采样", CacheSystemControl.E_SamplingSerialjob ? "连续" : "封装完成后"));
            DAL.SqlLite.Main.Instance.LogWrite(SysLogType.Login, string.Format("设定当前{0}采样", CacheSystemControl.E_SamplingSerialjob ? "连续" : "封装完成后"));
        }

        private void y(object sender, EventArgs e)
        {

        }

        private void ckBoxTestMode_CheckedChanged(object sender, EventArgs e)
        {
            _bIsTest = ckBoxTestMode.Checked;
            if (_bIsTest)
            {
                txtCarno.Text = "test";
                txtHeight.Text = "1.40";
                cbAotoSampling.Checked = false;
                cbAotoReadCard.Checked = false;
                cbSerialJob.Checked = false;
            }
            else
            {
                txtCarno.Text = "";
                txtHeight.Text = "";
            }
            FormHelper.ApplicationShow(UI.MsgType.Error, string.Format("选择{0}测试模式", ckBoxTestMode.Checked ? "启用" : "停用"));
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLift_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否确定抬杆?请确保当前车辆样品已成功进入封装机当中!", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                DAL.SqlLite.Main.Instance.LogWrite(SysLogType.Login, "出口手动抬杆");

                if (!Task.Cyj.Instance.DoWrite(100, (short)100))
                    UI.MsgBox.Show(UI.MsgType.Error, "抬杆命令下达失败！建议重新操作!");
            }
        }

        List<string> _listWasteWaring = null;
        private void DoJudgeWaste()
        {
            _tabWaste = DAL.SqlLite.Main.Instance.DoQueryWasteWaringJudgeParms();
            if (_tabWaste != null && _tabWaste.Rows.Count == 1)
            {
                _iWasteSet = int.Parse(_tabWaste.Rows[0]["WasteCount"].ToString());
                _iWasteCurrent = int.Parse(_tabWaste.Rows[0]["WasteCurrent"].ToString());
                if (_iWasteCurrent >= _iWasteSet)
                {
                    _listWasteWaring = new List<string>();
                    _listWasteWaring.Add("1、当前为弃料预警，提醒采样员关注弃料仓是否已满;");
                    _listWasteWaring.Add(string.Format("2、系统当前设置采样【{0}】车后开始关注弃料仓;", _iWasteSet));
                    _listWasteWaring.Add(string.Format("3、系统当前已成功采样【{0}】车;", _iWasteSet));
                    _listWasteWaring.Add("4、弃料仓检查完成后，可点击菜单【辅助告警】-【弃料完成】解除报警;");
                    _listWasteWaring.Add("5、若报警阈值与实际偏差较大，可适当调整阈值;");
                    ActionCenter.Action.Instance.DoSendWarings(_listWasteWaring, false);
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmSamplingCar_FormClosing(object sender, FormClosingEventArgs e)
        {
            UI_Operate.DataUpload.DoStop();
        }

        private void btnSendLayingOffComplete_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("当前操适用于封装机自动放样失败，系统触发二次放样！\r\n建议操作前先将封装机复位！\r\n是否确定继续操作？", "提示信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                //ActionCenter.Action.Instance.DoSendLayingOffComplete();
                //刷新样桶界面
                ActionCenter.Action.Instance.DoRefreshSamplingPail();
                //触发放样
                ActionCenter.Action.Instance.DoSamplingAndMakeingEnd();
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="send"></param>
        /// <param name="e"></param>
        bool _bIsBusy = false;
        /// <summary>
        /// 是否为测试模式 只采样 不监听
        /// </summary>
        bool _bIsTest = false;
        private void OnPlcDataReadOut(object send, Task.ActiveReadEventArgs e)
        {

            if (_bIsBusy)
                return;
            try
            {
                _bIsBusy = true;
                short[] _arrReads = (short[])e.E_ReadValue;
                int[] _aryBits330 = DataConvert.Ushort2Binary((int)(_arrReads[30 / 2]));
                int[] _aryBits334 = DataConvert.Ushort2Binary((int)(_arrReads[34 / 2]));
                int[] _aryBits354 = DataConvert.Ushort2Binary((int)(_arrReads[54 / 2]));
                int[] _aryBits360 = DataConvert.Ushort2Binary((int)(_arrReads[60 / 2]));

                //当前是否设定触底反弹
                CacheSystemControl.E_ButtomUp = ((int)_arrReads[110 / 2]) == 110;

                //运行
                E_SamplingRuning = _aryBits330[0] == 0;

                //采样结束回卸样点 集料斗打开 记录皮重 
                //_aryBits330[11] 自动采样 集料斗打开流程
                //_aryBits360[1] 大车卸样点
                if (_aryBits330[11] == 1 && _aryBits360[1] == 1)
                {
                    if (!_bSaveSampleTare)
                    {
                        ActionCenter.Action.Instance.DoWeightSampleTare();
                        _bSaveSampleTare = true;
                    }
                }
                else
                    _bSaveSampleTare = false;

                //采样准备好
                E_SamplingAlready = _aryBits330[3] == 1;
                DoSetAutoButtonStyle(E_SamplingAlready);

                //采样完成
                E_SamplingComplete = _aryBits334[0] == 1;

                //设置暂停按钮显示
                DoSetButtonPauseStyle(E_SamplingRuning);

                //设置半自动操作按钮
                if (_aryBits354[0] == 1)
                    E_SamplingType = SamplingType.Manual;
                else if (_aryBits354[1] == 1)
                    E_SamplingType = SamplingType.HalfAuto;
                else if (_aryBits354[2] == 1)
                    E_SamplingType = SamplingType.Auto;
                DoSetHalfAutoButtonStyle(E_SamplingType == SamplingType.HalfAuto);

                //测试模式  监听到此位置
                if (_bIsTest)
                    return;

                #region 司机触发采样 新逻辑
                //司机触发采样
                if (_aryBits334[6] == 1)
                {
                    if (_bCapCaptureCarNo)
                    {
                        FormHelper.ApplicationShow(UI.MsgType.Information, "司机采样：当前采样流程尚未结束，请勿重复点击按钮");
                        Thread.Sleep(6000);//休眠6秒
                        return;
                    }
                    _bCapCaptureCarNo = true;



                    if (!E_SamplingCarNumByCard)// 车牌识别模式
                    {
                        FormHelper.ApplicationShow(UI.MsgType.Information, "司机采样：抓拍车牌");
                        //将上一次记录的车牌数据清空，防止车牌识别错误的情况下不能进行第二次识别
                        E_CurrentCarLast = "";
                        E_CurrentCardLast = "";
                        ActionCenter.Action.Instance.DoCaptureCarNo();
                        Thread.Sleep(3000);
                    }
                    else
                    {//读卡模式
                        if (string.IsNullOrEmpty(E_CurrentCarNum))
                        {
                            FormHelper.ApplicationShow(UI.MsgType.Information, "司机采样：请先刷卡");
                            _bCapCaptureCarNo = false;//解除司机按钮防误触锁定
                            Thread.Sleep(6000);//休眠6秒
                            return;
                        }
                    }

                    //if (E_CurrentCarNum == E_CurrentCarLast)
                    //{
                    //    FormHelper.ApplicationShow(UI.MsgType.Information, "司机采样：尚未监测到车号变更");
                    //    _bCapCaptureCarNo = false;//解除司机按钮防误触锁定
                    //    return;
                    //}

                    //E_CurrentCarLast = E_CurrentCarNum;
                    if (!string.IsNullOrEmpty(E_CurrentCarNum))
                    {
                        FormHelper.ApplicationShow(UI.MsgType.Waring, string.Format("司机采样：当前车牌识别采用[{0}]模式，识别到车号[{1}]", (E_SamplingCarNumByCard ? "读卡" : "视频识别"), E_CurrentCarNum));
                        FormHelper.ApplicationShow(UI.MsgType.Information, $"司机采样：开始采样 {E_CurrentCarNum}");
                        EventHelper.DispatchEventAsync<ActionCenter.CommonEventArgs>(this, this.VehicleNumberIdentificationEvent, new ActionCenter.CommonEventArgs(E_CurrentCarNum));
                    }

                }
                #endregion

                /*
                * 肖波 23-03-09
                * 收到采样完成信号，开始保存数据
                */
                if (_aryBits334[0] == 1)
                {
                    if (!_bSaveSendDataPacking)
                    {
                        CacheSamplingPacking.E_PackingSaveValueSet = _modelSave;
                        _bSaveSendDataPacking = true;
                    }

                    ///采样完成提交数据
                    if (!_bSaveSamplingComplete)
                    {
                        FormHelper.ApplicationShow(UI.MsgType.Information, "收到采样完成信号，开始保存当前采样数据");
                        if (DAL.SqlLite.Main.Instance.DoUpdateSamplingEnd(E_CurrentSamplingIdOfLocal, E_SamplingPail))
                        {
                            FormHelper.ApplicationShow(UI.MsgType.Information, "采样完成状态本地系统更新成功");
                            if (!CacheSystemControl.E_ConnectWl)
                                _bSaveSamplingComplete = true;
                        }
                        else
                            FormHelper.ApplicationShow(UI.MsgType.Error, "采样完成状态本地系统更新失败!详见日志");

                        if (CacheSystemControl.E_ConnectWl)
                        {
                            if (DAL.Sqlserver.Interface.Instance.DoUpdateSamplingEndToWl(E_CurrentSamplingCardNo))
                            {
                                FormHelper.ApplicationShow(UI.MsgType.Error, "采样完成状态系统更新至物流系统");
                                //语音播报 
                                if (CacheSystemControl.E_SamplingSerialjob)
                                {
                                    Voicer.Instance.DoSendSound("采样完成，司机请尽快驶离当前区域");
                                    if (!Task.Cyj.Instance.DoWrite(100, (short)100))
                                        FormHelper.ApplicationShow(UI.MsgType.Error, "出口道闸抬杆失败!建议手动抬杆!");
                                }
                                else
                                    Voicer.Instance.DoSendSound("采样完成，样品正在封装，司机请等候");
                                _bSaveSamplingComplete = true;
                            }
                            else
                                FormHelper.ApplicationShow(UI.MsgType.Error, "采样完成状态系统更新至物流系统失败!详见日志");
                        }
                    }

                    ///采样完成保存采样图片
                    if (!_bSaveSamplingImage)
                    {
                        FormHelper.ApplicationShow(UI.MsgType.Information, "收到采样完成信号，开始保存采样完成后图片");
                        //截图
                        LiveShow.DoCatchImage(ref E_CurrentImage, "", false, false);
                        MemoryStream memoryStream = new MemoryStream();
                        if (E_CurrentImage == null)
                        {
                            FormHelper.ApplicationShow(UI.MsgType.Error, "抓图失败：无法获取视频截图。");
                            return;
                        }
                        else
                        {
                            E_CurrentImage = DoDrawString(E_CurrentImage, E_CurrentDrawString, Color.Yellow, 20);
                            E_CurrentImage.Save(memoryStream, ImageFormat.Jpeg);
                        }

                        if (DAL.SqlLite.Main.Instance.DoInsertImages(ImageSaver.DoSaveImage(E_CurrentSamplingIdOfLocal, E_CurrentImage, false), false, E_CurrentSamplingIdOfLocal))
                            FormHelper.ApplicationShow(UI.MsgType.Information, "采样完成后图片本地保存成功");
                        else
                            FormHelper.ApplicationShow(UI.MsgType.Error, "采样完成后图片本地保存出错!详见日志");
                        memoryStream = null;

                        //释放对象
                        E_CurrentImage = null;
                        //标记成功
                        _bSaveSamplingImage = true;
                    }

                    if (_bSaveSamplingComplete)
                    {
                        UI.FormHelper.SetComboxTextForFind(txtProvince, "冀");
                        UI.FormHelper.SetControlText(txtCarno, string.Empty);
                        UI.FormHelper.SetControlText(txtMin, string.Empty);
                        UI.FormHelper.SetControlText(txtMaterial, string.Empty);
                        UI.FormHelper.SetControlText(txtSupplier, string.Empty);
                        UI.FormHelper.SetControlText(txtTrifficUnit, string.Empty);

                        UI.FormHelper.SetControlText(txtSamplingCode, string.Empty);
                        UI.FormHelper.SetControlText(txtTotalLength, string.Empty);
                        UI.FormHelper.SetControlText(txtLength, string.Empty);
                        UI.FormHelper.SetControlText(txtWidth, string.Empty);
                        //UI.FormHelper.SetControlText(txtHeight, string.Empty);
                        UI.FormHelper.SetControlText(txtPostions, string.Empty);
                    }
                    _bCapCaptureCarNo = false;//解除司机按钮防误触锁定
                }

                /*
               * 肖波 23-03-09
               * 收到制样完成信号，开始转桶放料
               */
                if (_aryBits334[1] == 1)
                {
                    if (!_bSaveSendCommandPacking)
                    {
                        FormHelper.ApplicationShow(UI.MsgType.Information, "收到制样完成信号，开始转桶放样");

                        //制样完成后称毛重
                        ActionCenter.Action.Instance.DoWeightSampleGross();
                        //刷新样桶界面
                        ActionCenter.Action.Instance.DoRefreshSamplingPail();
                        //触发放样
                        ActionCenter.Action.Instance.DoSamplingAndMakeingEnd();
                        _bSaveSendCommandPacking = true;
                    }
                    System.Threading.Thread.Sleep(500);
                }
                else
                    _bSaveSendCommandPacking = false;

                try
                {
                    //if (_arrReads[100 / 2] != Convert.ToInt16(CacheMemoryCenter.E_PackingMachineState.自动准备好))
                    if (CacheMemoryCenter.E_SampleWeight > CacheSystemControl.E_AlreadyJudgeWeight)
                        Task.Cyj.Instance.DoWrite(400, Convert.ToInt16(false));
                    else
                        Task.Cyj.Instance.DoWrite(400, Convert.ToInt16(CacheMemoryCenter.E_PackingMachineState.自动准备好));
                }
                catch
                {
                    FormHelper.ApplicationShow(UI.MsgType.Error, "往采样机写入当前封装机状态失败!");
                }
            }
            catch (Exception ex)
            {
                FormHelper.ApplicationShow(UI.MsgType.Error, "窗体frmSamplingCar数据解析出错!详见日志");
                Log.LogHelper.DoWriteLogTypeSubitem(Log.LogType.Error, Log.LogSubitem.Forms, "窗体frmSamplingCar数据解析出错");
                Log.LogHelper.DoWriteLogTypeSubitem(Log.LogType.Error, Log.LogSubitem.Forms, ex.ToString());
            }
            finally
            {
                _bIsBusy = false;
            }
        }

        /// <summary>
        /// 往图片绘制文字
        /// </summary>
        /// <param name="img"></param>
        /// <param name="str"></param>
        private Image DoDrawString(Image img, string str, Color co, int fontsize)
        {
            if (img != null)
            {
                Graphics g = Graphics.FromImage(img);
                Font font = new Font("宋体", fontsize, FontStyle.Bold);
                SolidBrush sbrush = new SolidBrush(co);
                g.DrawString(str, font, sbrush, new PointF(10, 10));
            }
            return img;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="listPos"></param>
        /// <returns></returns>
        private string DoGetPosintString(List<Entity.SamplingPos> listPos)
        {
            string _strStr = "";
            for (int i = 1; i <= listPos.Count; i++)
            {
                _strStr += i.ToString() + ",";
                _strStr += listPos[i - 1].BlockNumber.ToString() + ",";
                _strStr += listPos[i - 1].X.ToString() + ",";
                _strStr += listPos[i - 1].Y.ToString() + ",";
                _strStr += listPos[i - 1].Z.ToString() + "*";
            }
            return _strStr;
        }


        /// <summary>
        /// 开启或者关闭读卡器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbAotoReadCard_CheckedChanged(object sender, EventArgs e)
        {
            if (cbAotoReadCard.Checked)
            {
                E_SamplingCarNumByCard = true;
                if (Card.MfMain.Instance.DoStartRead(E_MfCom, E_MfBrandRate))
                    FormHelper.ApplicationShow(UI.MsgType.Information, "读卡器启动成功.");
            }
            else
            {
                E_SamplingCarNumByCard = false;
                //停止读卡
                Card.MfMain.Instance.DoStopRead();
            }

            DAL.SqlLite.Main.Instance.LogWrite(SysLogType.Login, string.Format("选择{0}读卡采样", cbAotoReadCard.Checked ? "启用" : "停用"));

        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbAotoSampling_CheckedChanged(object sender, EventArgs e)
        {
            E_SamplingAoto = cbAotoSampling.Checked;
            DAL.SqlLite.Main.Instance.LogWrite(SysLogType.Login, string.Format("选择{0}司机自助采样", cbAotoReadCard.Checked ? "启用" : "停用"));
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (E_CrrentListSamplingPos != null)
            {
                E_CrrentListSamplingPos = DoAvoidLacingWire(E_CurtainCount, E_CurrentSamplingInfo, E_CrrentListSamplingPos);
            }
            return;
            FormHelper.ApplicationShow(UI.MsgType.Information, "收到制样完成信号，开始转桶放样");
            //制样完成后称毛重
            ActionCenter.Action.Instance.DoWeightSampleGross();
            //刷新样桶界面
            ActionCenter.Action.Instance.DoRefreshSamplingPail();
            //触发放样
            ActionCenter.Action.Instance.DoSamplingAndMakeingEnd();
            return;
            ActionCenter.Action.Instance.DoSetCarNum(DiscriminateType.LprCapture, "冀BC8146", false);
            //ActionCenter.Action.Instance.DoSetCarNum(DiscriminateType.CardRead, "6BDAD6E4", false);
            //Voicer.Instance.DoSendSound("测试语音播报！");
        }

        /// <summary>
        /// 当前布点方式
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtLayoutType_SelectedIndexChanged(object sender, EventArgs e)
        {
            //判断当前布点方式
            switch (txtLayoutType.SelectedIndex)
            {
                case 0:
                    E_CurrentLayoutType = SamplingPosMakeType.GB_EquaRand;
                    break;
                case 1:
                    E_CurrentLayoutType = SamplingPosMakeType.GB_FullRand;
                    break;
                default:
                    E_CurrentLayoutType = SamplingPosMakeType.KD_3PartRand;
                    break;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtPosCount_SelectedIndexChanged(object sender, EventArgs e)
        {
            E_SamplingPosCount = int.Parse(txtPosCount.Text);
        }

        #region 从三级编码系统获取物流信息
        /// <summary>
        /// 从本地数据库提取物流信息
        /// </summary>
        /// <param name="isAoto">False手动刷新车牌，Ture 自动识别车牌</param>
        public void DoExtractDataFromSystem(bool isAoto)
        {
            try
            {
                E_CurrentSamplingInfo = null;
                _bSamplingInfoCheckOut = false;
                ActionCenter.Action.Instance.DoCatchImageCarHead();
                //step1:判断输入参数是否合理
                if (string.IsNullOrEmpty(E_CurrentCarNum))
                {
                    DoShowMsgByOperateType(isAoto, UI.MsgType.Waring, "车号不能为空");
                    _bCapCaptureCarNo = false;//解除司机按钮防误触锁定
                    return;
                }

                //step2:从本地接口获取数据
                Entity.SamplingInfo _modelInfo = DAL.SqlLite.Main.Instance.DoSendRequest(E_CurrentCarNum);

                ////step3:判断是否为无人值守模拟环境，替换原有车辆信息 Test_CarInfo
                //Entity.SamplingInfo _textModel = DAL.SqlLite.Main.Instance.GetTestCarInfo(E_CurrentCarNum);

                if (_modelInfo != null)
                {
                    if (_modelInfo.En_Success)
                    {
                        ////如果是无人值守模拟模式 则将本地模拟数据替换
                        //if (CacheMemoryCenter.E_Unmanned)
                        //{
                        //    FormHelper.ApplicationShow(UI.MsgType.Information, $"读取车型模拟数据");
                        //    FormHelper.ApplicationShow(UI.MsgType.Information, $"启用车型数据模拟：{_textModel.ToJsonEx()}");
                        //    _modelInfo.En_TotleLength = _textModel.En_TotleLength;
                        //    _modelInfo.En_TotleWidth = _textModel.En_TotleWidth;
                        //    _modelInfo.En_Length = _textModel.En_Length;
                        //    _modelInfo.En_Width = _textModel.En_Width;
                        //    _modelInfo.En_Height = _textModel.En_Height;
                        //    _modelInfo.En_Postions = _textModel.En_Postions;
                        //}
                        //车头保护值检测
                        //if ((_modelInfo.En_TotleLength - _modelInfo.En_Length) < CarHeadProtectLength)
                        //{
                        //    _bCapCaptureCarNo = false;//解除司机按钮防误触锁定
                        //    FormHelper.ApplicationShow(UI.MsgType.Error, $"车型数据异常，车长:{_modelInfo.En_TotleLength},车厢长：{_modelInfo.En_Length},车头长：{(_modelInfo.En_TotleLength - _modelInfo.En_Length)} 小于正常车长{CarHeadProtectLength}");
                        //    return;
                        //}

                        E_CurrentSamplingCardNo = _modelInfo.En_PrimaryKey;
                        CacheMemoryCenter.E_SamplingInfo = _modelInfo;
                        //显示数据到界面
                        UI.FormHelper.SetComboxTextForFind(txtProvince, _modelInfo.En_Car.Substring(0, 1));
                        UI.FormHelper.SetControlText(txtCarno, _modelInfo.En_Car.Substring(1, _modelInfo.En_Car.Length - 1));
                        UI.FormHelper.SetControlText(txtMin, CacheUser.E_KeyInformation ? _modelInfo.En_MineName : "*****");
                        UI.FormHelper.SetControlText(txtMaterial, CacheUser.E_KeyInformation ? _modelInfo.En_MaterielName : "*******");
                        UI.FormHelper.SetControlText(txtSupplier, CacheUser.E_KeyInformation ? _modelInfo.En_SupplierName : "**********");
                        UI.FormHelper.SetControlText(txtTrifficUnit, CacheUser.E_KeyInformation ? _modelInfo.En_TransportName : "**********");

                        UI.FormHelper.SetControlText(txtSamplingCode, _modelInfo.En_Batch.ToStringEx());
                        UI.FormHelper.SetControlText(txtTotalLength, _modelInfo.En_TotleLength.ToStringEx());
                        UI.FormHelper.SetControlText(txtLength, _modelInfo.En_Length.ToStringEx());
                        UI.FormHelper.SetControlText(txtWidth, _modelInfo.En_Width.ToStringEx());
                        //UI.FormHelper.SetControlText(txtHeight, _modelInfo.En_Height.ToStringEx());
                        //UI.FormHelper.SetControlText(txtHeight, _modelInfo.En_Length <= 0 ? "1.75" : _modelInfo.En_Length.ToString());
                        UI.FormHelper.SetControlText(txtPostions, _modelInfo.En_Postions.ToStringEx());
                        FormHelper.ApplicationShow(UI.MsgType.Information, $"司机触发采样：界面渲染完成");
                        //FormHelper.ApplicationShow(UI.MsgType.Information, $"司机触发采样：{_modelInfo.ToJsonEx()}");
                        //当前获取到批次号
                        if (!string.IsNullOrEmpty(_modelInfo.En_Batch))
                            E_CurrentSamplingInfo = _modelInfo;

                        _bSamplingInfoCheckOut = DoCheckOutSamplingInfo(isAoto, _modelInfo);
                        if (isAoto)
                        {
                            System.Threading.Thread.Sleep(50);
                            if (_bSamplingInfoCheckOut)//采样基础信息校验通过
                            {
                                //采样基础信息校验通过才会渲染高度，画框采样模式采样基础信息校验不通过则不会改界面高度，避免操作员频繁选择高度
                                UI.FormHelper.SetControlText(txtHeight, _modelInfo.En_Height.ToStringEx());
                                //如果 自动采样（司机采样）
                                if (E_SamplingAoto)
                                {
                                    DoStartSamplingAoto(_modelInfo);
                                    //if ( CacheMemoryCenter.E_NoSampling != 1)
                                    //{
                                    //    //这里开始自动采样流程
                                    //    DoStartSamplingAoto(_modelInfo);
                                    //}
                                    //else
                                    //{
                                    //    FormHelper.ApplicationShow(UI.MsgType.Information, $"司机触发采样：测试模式，不采样...");
                                    //    _bCapCaptureCarNo = false;//解除司机按钮防误触锁定
                                    //}
                                }
                            }
                            else
                            {
                                _bCapCaptureCarNo = false;//解除司机按钮防误触锁定
                                DoShowMsgByOperateType(true, UI.MsgType.Error, "物流信息校验不通过，无法继续自动采样流程");
                            }
                        }
                    }
                    else
                    {
                        DoShowMsgByOperateType(isAoto, UI.MsgType.Error, "从物流系统提取车辆数据失败！" + _modelInfo.En_FullDesc);
                        E_CurrentCardLast = string.Empty;
                        _bCapCaptureCarNo = false;//解除司机按钮防误触锁定
                    }
                }
                else
                {
                    DoShowMsgByOperateType(isAoto, UI.MsgType.Error, "从物流系统提取车辆数据失败，建议优先排查网络故障！");
                    E_CurrentCardLast = string.Empty;
                    _bCapCaptureCarNo = false;//解除司机按钮防误触锁定
                }
            }
            catch (Exception ex)
            {
                DoShowMsgByOperateType(isAoto, UI.MsgType.Error, "从物流系统提取车辆数据失败，发生未知异常！");
                DoShowMsgByOperateType(isAoto, UI.MsgType.Error, ex.ToString());
                E_CurrentCardLast = string.Empty;
                _bCapCaptureCarNo = false;//解除司机按钮防误触锁定
            }
        }

        /// <summary>
        /// 全自动采样
        /// </summary>
        /// <param name="_modelParms"></param>
        private void DoStartSamplingAoto(Entity.SamplingInfo _modelParms)
        {
            if (CacheUser.E_LockSampling)
            {
                DoShowMsgByOperateType(true, UI.MsgType.Error, "管理员账号已被禁止采样");
                _bCapCaptureCarNo = false;//解除司机按钮防误触锁定
                return;
            }
            if (E_SamplingPosCount <= 0)
            {
                DoShowMsgByOperateType(true, UI.MsgType.Error, "无法自动获取采样点数");
                _bCapCaptureCarNo = false;//解除司机按钮防误触锁定
                return;
            }

            //根据批次号提取合适的样桶
            decimal _dSampleWeightHistory = DAL.SqlLite.Main.Instance.DoGetSampleWeight(_modelParms.En_Materiel, _modelParms.En_Supplier);
            FormHelper.ApplicationShow(UI.MsgType.Error, string.Format("获取到同物料同供应商的历史平均采样量{0}kg", _dSampleWeightHistory));
            E_SamplingPail = DAL.SqlLite.Main.Instance.DoGetPailForSampling(_modelParms.En_Batch, E_SamplingPosCount, CacheSamplingPacking.DoGetCachePointCount(), _dSampleWeightHistory);
            if (E_SamplingPail <= 0)
            {
                _bCapCaptureCarNo = false;//解除司机按钮防误触锁定
                DoShowMsgByOperateType(true, UI.MsgType.Error, "当前样桶不足，请及时更换");
            }
            else
            {
                //错误屏蔽 把桶号数据给了采样点位
                //UI.FormHelper.SetComboxTextForFind(txtPosCount, E_SamplingPail.ToString()); 
                //显示当前采样信息
                DoShowMsgByOperateType(true, UI.MsgType.Information, string.Format("车号:{0}", _modelParms.En_Car));
                DoShowMsgByOperateType(true, UI.MsgType.Information, string.Format("整车长度:{0}", _modelParms.En_TotleLength));
                DoShowMsgByOperateType(true, UI.MsgType.Information, string.Format("车厢长度:{0}", _modelParms.En_Length));
                DoShowMsgByOperateType(true, UI.MsgType.Information, string.Format("车厢宽度:{0}", _modelParms.En_Width));
                DoShowMsgByOperateType(true, UI.MsgType.Information, string.Format("车厢底高:{0}", _modelParms.En_Height));
                DoShowMsgByOperateType(true, UI.MsgType.Information, string.Format("拉筋位置:{0}", _modelParms.En_Postions));
                #region 生成采样点
                /*
                 * 自动生成采样点的话
                 * 先计算车辆在现有采样区域下的实际物理空间坐标
                 * 这里主要计算车厢前后空间坐标，以及车辆左右的物理空间坐标
                 * 车辆的前后空间坐标，是以光幕原点作为参照
                 * 用decimal类型进行计算
                 * 激光测距在真实测量数据基础上，增加8mm的保护
                 */
                int _iCurtainCount = E_CurtainCount;
                double _dLaserSpace = E_LaserSpace;
                DoShowMsgByOperateType(true, UI.MsgType.Error, string.Format("激光测距距离:{0}", E_LaserSpace));
                DoShowMsgByOperateType(true, UI.MsgType.Error, string.Format("光栅遮挡点数:{0}", _iCurtainCount));
                double _dCxBegin = Convert.ToDouble(_modelParms.En_TotleLength * 1000 - _modelParms.En_Length * 1000) - ((E_XGA_Count - _iCurtainCount) * E_XGA_Space) - E_Aoto_XBegin_Space;
                double _dCxEnd = Convert.ToDouble(_modelParms.En_TotleLength * 1000) - ((E_XGA_Count - _iCurtainCount) * E_XGA_Space) - E_Aoto_XBegin_Space;
                double _dCxLeft = _dLaserSpace * 1000 + 100 + 100;
                double _dCxBase = E_Aoto_YBeginSpace;
                double _dCxRight = _dLaserSpace * 1000 + 100 + Convert.ToDouble(_modelParms.En_Width * 1000) - 100;
                if (CacheMemoryCenter.E_IsDebug)
                    DoShowMsgByOperateType(true, UI.MsgType.Information, string.Format("空间 XB:{0}  XE:{1} YB:{2} YE:{3}", _dCxBegin, _dCxEnd, _dCxLeft, _dCxRight));

                //起点向上取整，终点向下取整
                E_X_Begin = Convert.ToInt32(System.Math.Ceiling(E_Aoto_XBegin + _dCxBegin / E_Aoto_XPulse));
                E_X_End = Convert.ToInt32(System.Math.Floor(E_Aoto_XBegin + _dCxEnd / E_Aoto_XPulse));
                //E_Aoto_YBegin 大车相对光幕的起点脉冲 130
                E_Y_Begin = Convert.ToInt32(System.Math.Ceiling(E_Aoto_YBegin + (_dCxLeft - _dCxBase) / E_Aoto_YPulse));
                E_Y_End = Convert.ToInt32(System.Math.Floor(E_Aoto_YBegin + (_dCxRight - _dCxBase) / E_Aoto_YPulse));
                if (CacheMemoryCenter.E_IsDebug)
                    DoShowMsgByOperateType(true, UI.MsgType.Information, string.Format("计算1 XB:{0}  XE:{1} YB:{2} YE:{3}", E_X_Begin, E_X_End, E_Y_Begin, E_Y_End));

                if (E_X_Begin > E_X_End)
                {
                    E_X_Begin ^= E_X_End;
                    E_X_End ^= E_X_Begin;
                    E_X_Begin ^= E_X_End;
                }
                if (E_Y_Begin > E_Y_End)
                {
                    E_Y_Begin ^= E_Y_End;
                    E_Y_End ^= E_Y_Begin;
                    E_Y_Begin ^= E_Y_End;
                }
                if (CacheMemoryCenter.E_IsDebug)
                    DoShowMsgByOperateType(true, UI.MsgType.Information, string.Format("计算2 XB:{0}  XE:{1} YB:{2} YE:{3}", E_X_Begin, E_X_End, E_Y_Begin, E_Y_End));

                E_X_Begin += E_xProtect;
                E_Y_Begin += E_yProtect;
                E_X_End -= E_xProtect;
                E_Y_End -= E_yProtect;

                if (CacheMemoryCenter.E_IsDebug)
                    DoShowMsgByOperateType(true, UI.MsgType.Information, string.Format("保护1 XB:{0}  XE:{1} YB:{2} YE:{3}", E_X_Begin, E_X_End, E_Y_Begin, E_Y_End));

                if (E_X_Begin < E_xMin)
                    E_X_Begin = E_xMin;
                if (E_X_End > E_xMax)
                    E_X_End = E_xMax;
                if (E_Y_Begin < E_yMin)
                    E_Y_Begin = E_yMin;
                if (E_Y_End > E_yMax)
                    E_Y_End = E_yMax;

                if (CacheMemoryCenter.E_IsDebug)
                    DoShowMsgByOperateType(true, UI.MsgType.Information, string.Format("终值 XB:{0}  XE:{1} YB:{2} YE:{3}", E_X_Begin, E_X_End, E_Y_Begin, E_Y_End));

                //生成采样点
                Share.SamplingPosGen samplingPosGen = new Share.SamplingPosGen(E_X_Begin, E_X_End, E_Y_Begin, E_Y_End, DoCalculatedHeight(Convert.ToDouble(_modelParms.En_Height)), 0, 0);
                //E_CrrentListSamplingPos = samplingPosGen.MakeSamplingPos(E_SamplingPosCount, E_CurrentLayoutType);
                //拉筋不为空 拉筋规避
                if (!string.IsNullOrEmpty(_modelParms.En_Postions.ToStringEx()) && _modelParms.En_Postions.ToStringEx() != "0")
                    E_CrrentListSamplingPos = DoAvoidLacingWire(_iCurtainCount, _modelParms, E_CrrentListSamplingPos);

                //随机分布采样块 18块均匀随机
                E_CrrentListSamplingPos = Coordinate(E_SamplingPosCount, DoCalculatedHeight(Convert.ToDouble(_modelParms.En_Height)));
                //随机分布 采样块
                E_CrrentListSamplingPos = samplingPosGen.ToRandomPos(E_CrrentListSamplingPos);

                #endregion

                if (E_CrrentListSamplingPos != null && E_CrrentListSamplingPos.Count > 0)
                {
                    //渲染布点
                    ActionCenter.Action.Instance.E_SamplingPos = E_CrrentListSamplingPos;
                    //弃料判断
                    DoJudgeWaste();
                    //自动启动采样
                    DoStartSamplingAoto();
                }
                else
                {
                    _bCapCaptureCarNo = false;//解除司机按钮防误触锁定
                    DoShowMsgByOperateType(true, UI.MsgType.Error, "拉筋数据计算出错，无法继续自动采样");
                }

            }
        }

        #region 18个块随机循环均匀布点

        /// <summary>
        /// 18个块随机循环均匀布点
        /// </summary>
        /// <param name="cyCount"></param>
        /// <returns></returns>
        public List<Entity.SamplingPos> Coordinate(int cyCount, int deep)
        {
            List<Entity.SamplingPos> listsamplingpost = new List<Entity.SamplingPos>();
            try
            {
                int x1 = E_X_Begin + ((E_X_End - E_X_Begin) % 6) / 2;
                int x2 = x1 + (E_X_End - E_X_Begin) / 6;
                int x3 = x2 + (E_X_End - E_X_Begin) / 6;
                int x4 = x3 + (E_X_End - E_X_Begin) / 6;
                int x5 = x4 + (E_X_End - E_X_Begin) / 6;
                int x6 = x5 + (E_X_End - E_X_Begin) / 6;
                int x7 = x6 + (E_X_End - E_X_Begin) / 6;
                int y1 = E_Y_Begin + ((E_Y_End - E_Y_Begin) % 3) / 2;
                int y2 = y1 + (E_Y_End - E_Y_Begin) / 3;
                int y3 = y2 + (E_Y_End - E_Y_Begin) / 3;
                int y4 = y3 + (E_Y_End - E_Y_Begin) / 3;
                List<int> rdata = GetNum(cyCount);
                rdata.Sort();
                foreach (int quyu in rdata)
                {
                    Entity.SamplingPos pos = new Entity.SamplingPos();
                    pos.BlockNumber = quyu;
                    if (pos.BlockNumber == 1)
                    {
                        ////假如采样区域是1，
                        pos.XBegin = x1;
                        pos.YBegin = y1;
                        //pos.Z = E_CurrentSamplingDeep;
                        pos.XEnd = x2;
                        pos.YEnd = y2;
                        //pos.Z = E_CurrentSamplingDeep;
                        pos.X = new Random(Guid.NewGuid().GetHashCode()).Next(x1, x2);
                        pos.Y = new Random(Guid.NewGuid().GetHashCode()).Next(y1, y2);
                        pos.Z = deep;
                    }
                    else if (pos.BlockNumber == 2)
                    {
                        ////假如采样区域是2，
                        pos.XBegin = x1;
                        pos.YBegin = y2;
                        //pos.MinZ = E_CurrentSamplingDeep;
                        pos.XEnd = x2;
                        pos.YEnd = y3;
                        //pos.MaxZ = E_CurrentSamplingDeep;
                        pos.X = new Random(Guid.NewGuid().GetHashCode()).Next(x1, x2);
                        pos.Y = new Random(Guid.NewGuid().GetHashCode()).Next(y2, y3);
                        pos.Z = deep;
                    }
                    else if (pos.BlockNumber == 3)
                    {
                        ////假如采样区域是3，
                        pos.XBegin = x1;
                        pos.YBegin = y3;
                        //pos.MinZ = E_CurrentSamplingDeep;
                        pos.XEnd = x2;
                        pos.YEnd = y4;
                        //pos.MaxZ = E_CurrentSamplingDeep;
                        pos.X = new Random(Guid.NewGuid().GetHashCode()).Next(x1, x2);
                        pos.Y = new Random(Guid.NewGuid().GetHashCode()).Next(y3, y4);
                        pos.Z = deep;
                    }
                    else if (pos.BlockNumber == 4)
                    {
                        ////假如采样区域是4，
                        pos.XBegin = x2;
                        pos.YBegin = y1;
                        //pos.MinZ = E_CurrentSamplingDeep;
                        pos.XEnd = x3;
                        pos.YEnd = y2;
                        //pos.MaxZ = E_CurrentSamplingDeep;
                        pos.X = new Random(Guid.NewGuid().GetHashCode()).Next(x2, x3);
                        pos.Y = new Random(Guid.NewGuid().GetHashCode()).Next(y1, y2);
                        pos.Z = deep;
                    }
                    else if (pos.BlockNumber == 5)
                    {
                        ////假如采样区域是5，
                        pos.XBegin = x2;
                        pos.YBegin = y2;
                        //pos.MinZ = E_CurrentSamplingDeep;
                        pos.XEnd = x3;
                        pos.YEnd = y3;
                        //pos.MaxZ = E_CurrentSamplingDeep;
                        pos.X = new Random(Guid.NewGuid().GetHashCode()).Next(x2, x3);
                        pos.Y = new Random(Guid.NewGuid().GetHashCode()).Next(y2, y3);
                        pos.Z = deep;
                    }
                    else if (pos.BlockNumber == 6)
                    {
                        ////假如采样区域是6，
                        pos.XBegin = x2;
                        pos.YBegin = y3;
                        //pos.MinZ = E_CurrentSamplingDeep;
                        pos.XEnd = x3;
                        pos.YEnd = y4;
                        //pos.MaxZ = E_CurrentSamplingDeep;
                        pos.X = new Random(Guid.NewGuid().GetHashCode()).Next(x2, x3);
                        pos.Y = new Random(Guid.NewGuid().GetHashCode()).Next(y3, y4);
                        pos.Z = deep;
                    }
                    else if (pos.BlockNumber == 7)
                    {
                        ////假如采样区域是7，
                        pos.XBegin = x3;
                        pos.YBegin = y1;
                        //pos.MinZ = E_CurrentSamplingDeep;
                        pos.XEnd = x4;
                        pos.YEnd = y2;
                        //pos.MaxZ = E_CurrentSamplingDeep;
                        pos.X = new Random(Guid.NewGuid().GetHashCode()).Next(x3, x4);
                        pos.Y = new Random(Guid.NewGuid().GetHashCode()).Next(y1, y2);
                        pos.Z = deep;
                    }
                    else if (pos.BlockNumber == 8)
                    {
                        ////假如采样区域是8，
                        pos.XBegin = x3;
                        pos.YBegin = y2;
                        //pos.MinZ = E_CurrentSamplingDeep;
                        pos.XEnd = x2;
                        pos.YEnd = y3;
                        //pos.MaxZ = E_CurrentSamplingDeep;
                        pos.X = new Random(Guid.NewGuid().GetHashCode()).Next(x3, x4);
                        pos.Y = new Random(Guid.NewGuid().GetHashCode()).Next(y2, y3);
                        pos.Z = deep;
                    }
                    else if (pos.BlockNumber == 9)
                    {
                        ////假如采样区域是9，
                        pos.XBegin = x3;
                        pos.YBegin = y3;
                        //pos.MinZ = E_CurrentSamplingDeep;
                        pos.XEnd = x4;
                        pos.YEnd = y4;
                        //pos.MaxZ = E_CurrentSamplingDeep;
                        pos.X = new Random(Guid.NewGuid().GetHashCode()).Next(x3, x4);
                        pos.Y = new Random(Guid.NewGuid().GetHashCode()).Next(y3, y4);
                        pos.Z = deep;
                    }
                    else if (pos.BlockNumber == 10)
                    {

                        ////假如采样区域是10，
                        pos.XBegin = x4;
                        pos.YBegin = y1;
                        //pos.MinZ = E_CurrentSamplingDeep;
                        pos.XEnd = x5;
                        pos.YEnd = y2;
                        //pos.MaxZ = E_CurrentSamplingDeep;
                        pos.X = new Random(Guid.NewGuid().GetHashCode()).Next(x4, x5);
                        pos.Y = new Random(Guid.NewGuid().GetHashCode()).Next(y1, y2);
                        pos.Z = deep;
                    }
                    else if (pos.BlockNumber == 11)
                    {
                        ////假如采样区域是11，
                        pos.XBegin = x4;
                        pos.YBegin = y2;
                        //pos.MinZ = E_CurrentSamplingDeep;
                        pos.XEnd = x5;
                        pos.YEnd = y3;
                        //pos.MaxZ = E_CurrentSamplingDeep;
                        pos.X = new Random(Guid.NewGuid().GetHashCode()).Next(x4, x5);
                        pos.Y = new Random(Guid.NewGuid().GetHashCode()).Next(y2, y3);
                        pos.Z = deep;
                    }
                    else if (pos.BlockNumber == 12)
                    {
                        ////假如采样区域是12，
                        pos.XBegin = x4;
                        pos.XBegin = y3;
                        //pos.MinZ = E_CurrentSamplingDeep;
                        pos.XEnd = x5;
                        pos.YEnd = y4;
                        //pos.MaxZ = E_CurrentSamplingDeep;
                        pos.X = new Random(Guid.NewGuid().GetHashCode()).Next(x4, x5);
                        pos.Y = new Random(Guid.NewGuid().GetHashCode()).Next(y3, y4);
                        pos.Z = deep;
                    }
                    else if (pos.BlockNumber == 13)
                    {
                        ////假如采样区域是13，
                        pos.XBegin = x5;
                        pos.XEnd = y1;
                        //pos.MinZ = E_CurrentSamplingDeep;
                        pos.XEnd = x6;
                        pos.YEnd = y2;
                        //pos.MaxZ = E_CurrentSamplingDeep;
                        pos.X = new Random(Guid.NewGuid().GetHashCode()).Next(x5, x6);
                        pos.Y = new Random(Guid.NewGuid().GetHashCode()).Next(y1, y2);
                        pos.Z = deep;
                    }
                    else if (pos.BlockNumber == 14)
                    {
                        ////假如采样区域是14，
                        pos.XBegin = x5;
                        pos.YBegin = y2;
                        //pos.MinZ = E_CurrentSamplingDeep;
                        pos.XEnd = x6;
                        pos.YEnd = y3;
                        //pos.MaxZ = E_CurrentSamplingDeep;
                        pos.X = new Random(Guid.NewGuid().GetHashCode()).Next(x5, x6);
                        pos.Y = new Random(Guid.NewGuid().GetHashCode()).Next(y2, y3);
                        pos.Z = deep;
                    }
                    else if (pos.BlockNumber == 15)
                    {
                        ////假如采样区域是15，
                        pos.XBegin = x5;
                        pos.YBegin = y3;
                        //pos.MinZ = E_CurrentSamplingDeep;
                        pos.XEnd = x6;
                        pos.YEnd = y4;
                        //pos.MaxZ = E_CurrentSamplingDeep;
                        pos.X = new Random(Guid.NewGuid().GetHashCode()).Next(x5, x6);
                        pos.Y = new Random(Guid.NewGuid().GetHashCode()).Next(y3, y4);
                        pos.Z = deep;
                    }
                    else if (pos.BlockNumber == 16)
                    {
                        ////假如采样区域是16，
                        pos.XBegin = x6;
                        pos.YEnd = y1;
                        //pos.MinZ = E_CurrentSamplingDeep;
                        pos.XEnd = x7;
                        pos.YEnd = y2;
                        //pos.MaxZ = E_CurrentSamplingDeep;
                        pos.X = new Random(Guid.NewGuid().GetHashCode()).Next(x6, x7);
                        pos.Y = new Random(Guid.NewGuid().GetHashCode()).Next(y1, y2);
                        pos.Z = deep;
                    }
                    else if (pos.BlockNumber == 17)
                    {
                        ////假如采样区域是17，
                        pos.XBegin = x6;
                        pos.YBegin = y2;
                        //pos.MinZ = E_CurrentSamplingDeep;
                        pos.XEnd = x7;
                        pos.YEnd = y3;
                        //pos.MaxZ = E_CurrentSamplingDeep;
                        pos.X = new Random(Guid.NewGuid().GetHashCode()).Next(x6, x7);
                        pos.Y = new Random(Guid.NewGuid().GetHashCode()).Next(y2, y3);
                        pos.Z = deep;
                    }
                    else if (pos.BlockNumber == 18)
                    {
                        ////假如采样区域是18，
                        pos.XBegin = x6;
                        pos.YBegin = y3;
                        //pos.MinZ = E_CurrentSamplingDeep;
                        pos.XEnd = x7;
                        pos.YEnd = y4;
                        //pos.MaxZ = E_CurrentSamplingDeep;
                        pos.X = new Random(Guid.NewGuid().GetHashCode()).Next(x6, x7);
                        pos.Y = new Random(Guid.NewGuid().GetHashCode()).Next(y3, y4);
                        pos.Z = deep;
                    }
                    listsamplingpost.Add(pos);

                }
                //FormHelper.ApplicationShow(UI.MsgType.Error, "随机坐标：" + listsamplingpost.ToJsonEx());
                return listsamplingpost;
            }
            catch (Exception ex)
            {
                FormHelper.ApplicationShow(UI.MsgType.Error, "随机布点出错!详见日志");
                Log.LogHelper.DoWriteLogTypeSubitem(Log.LogType.Error, Log.LogSubitem.Forms, "随机布点出错");
                Log.LogHelper.DoWriteLogTypeSubitem(Log.LogType.Error, Log.LogSubitem.Forms, ex.ToString());
                return listsamplingpost;
            }
        }
        private List<int> IsExist = new List<int>();
        private List<int> list1 = new List<int>();
        private List<int> list2 = new List<int>();
        private List<int> list3 = new List<int>();
        private List<int> GetNum(int num)
        {
            List<int> result = new List<int>();
            try
            {
                if (num > 6 || num < 1)
                {
                    num = 1;
                }
                if (18 - IsExist.Count < num)
                {
                    IsExist.Clear();
                    InitData();
                    WriteData();
                }
                int total = IsExist.Count;
                for (int i = total + 1; i <= total + num; i++)
                {
                    int index = i % 3 - 1;
                    if (index < 0)
                    {
                        index = 2;
                    }
                    switch (index)
                    {
                        case 0:
                            int num1 = list1[new Random(Guid.NewGuid().GetHashCode()).Next(list1.Count)];
                            list1.Remove(num1);
                            result.Add(num1);
                            IsExist.Add(num1);
                            break;
                        case 1:
                            int num2 = list2[new Random(Guid.NewGuid().GetHashCode()).Next(list2.Count)];
                            list2.Remove(num2);
                            result.Add(num2);
                            IsExist.Add(num2);
                            break;
                        case 2:
                            int num3 = list3[new Random(Guid.NewGuid().GetHashCode()).Next(list3.Count)];
                            list3.Remove(num3);
                            result.Add(num3);
                            IsExist.Add(num3);
                            break;
                    }
                }
                WriteData();
            }
            catch (Exception ex)
            {
                FormHelper.ApplicationShow(UI.MsgType.Error, "GetNum!详见日志");
                Log.LogHelper.DoWriteLogTypeSubitem(Log.LogType.Error, Log.LogSubitem.Forms, "GetNum出错");
                Log.LogHelper.DoWriteLogTypeSubitem(Log.LogType.Error, Log.LogSubitem.Forms, ex.ToString());
            }
            return result;
        }

        private void InitData()
        {
            list1.Clear();
            list2.Clear();
            list3.Clear();
            for (int i = 1; i < 7; i++)
            {
                list1.Add(i);
                list2.Add(i + 6);
                list3.Add(i + 12);
            }
        }

        private void LoadData()
        {

            try
            {
                if (File.Exists("data.dt"))
                {
                    string str = File.ReadAllText("data.dt");
                    string[] tmp = str.Split(',');
                    foreach (string item in tmp)
                    {
                        int _num = 0;
                        if (int.TryParse(item, out _num))
                        {
                            IsExist.Add(_num);
                            if (list1.Contains(_num))
                            {
                                list1.Remove(_num);
                            }
                            if (list2.Contains(_num))
                            {
                                list2.Remove(_num);
                            }
                            if (list3.Contains(_num))
                            {
                                list3.Remove(_num);
                            }
                        }
                    }
                }
            }
            catch { }
        }

        private void WriteData()
        {

            try
            {
                string str = "";

                foreach (int item in IsExist)
                {
                    str += $"{item},";
                }
                File.WriteAllText("data.dt", str);

            }
            catch { }
        }

        #endregion

        /// <summary>
        /// 自动启动采样
        /// </summary>
        private void DoStartSamplingAoto()
        {
            if (E_CrrentListSamplingPos == null || E_CrrentListSamplingPos.Count < 1)
            {
                FormHelper.ApplicationShow(UI.MsgType.Error, "尚未生成布点方案，无法开始采样");
                _bCapCaptureCarNo = false;//解除司机按钮防误触锁定
                return;
            }

            if (E_CrrentListSamplingPos.Count != E_SamplingPosCount)
            {
                FormHelper.ApplicationShow(UI.MsgType.Error, "生成采样点数与选择采样点数不符，建议重新选择采样点后画框!");
                _bCapCaptureCarNo = false;//解除司机按钮防误触锁定
                return;
            }

            if (E_CurrentSamplingInfo == null)
            {
                FormHelper.ApplicationShow(UI.MsgType.Error, "采样信息不完整，无法开始采样");
                _bCapCaptureCarNo = false;//解除司机按钮防误触锁定
                return;
            }
            //根据批次号提取合适的样桶
            //根据批次号提取合适的样桶
            decimal _dSampleWeightHistory = DAL.SqlLite.Main.Instance.DoGetSampleWeight(E_CurrentSamplingInfo.En_Materiel, E_CurrentSamplingInfo.En_Supplier);
            FormHelper.ApplicationShow(UI.MsgType.Error, string.Format("获取到同物料同供应商的历史平均采样量{0}kg", _dSampleWeightHistory));
            E_SamplingPail = DAL.SqlLite.Main.Instance.DoGetPailForSampling(E_CurrentSamplingInfo.En_Batch, E_CurrentSamplingInfo.En_SamplingPosCount, CacheSamplingPacking.DoGetCachePointCount(), _dSampleWeightHistory);
            if (E_SamplingPail <= 0)
            {
                /*当前样桶已满，需要出桶*/
                FormHelper.ApplicationShow(UI.MsgType.Error, "已无样桶可用于当前采样");
                _bCapCaptureCarNo = false;//解除司机按钮防误触锁定
                return;
            }
            else
            {
                E_CurrentSamplingInfo.En_SamplingPail = E_SamplingPail;
                UI.FormHelper.SetComboxTextForFind(txtPail, E_SamplingPail.ToString());
            }

            //启用记忆缩分功能
            int _iSubdivision = 0;
            if (CacheSystemControl.E_MemoryReductionc)
            {
                _iSubdivision = DAL.SqlLite.Main.Instance.DoQuerySubdivisionForSamplings(E_CurrentSamplingInfo.En_Materiel, E_CurrentSamplingInfo.En_Supplier);
                if (_iSubdivision <= 0)
                    _iSubdivision = CacheSystemControl.E_ReductioncDefaultSet;
                if (_iSubdivision != CacheSystemControl.E_ReductioncCurrent)
                {
                    if (Task.Cyj.Instance.DoWrite(154, (short)_iSubdivision))
                    {
                        FormHelper.ApplicationShow(UI.MsgType.Waring, string.Format("系统当前启用记忆缩分功能，缩分间隔{0}设定成功", _iSubdivision));
                        System.Threading.Thread.Sleep(300);
                    }
                    else
                        FormHelper.ApplicationShow(UI.MsgType.Error, string.Format("系统当前启用记忆缩分功能，缩分间隔{0}设定失败", _iSubdivision));
                }
            }

            double _dTotalLength, _dCLength, _dCwidth, _dCheight;
            double.TryParse(E_CarTotalLength, out _dTotalLength);
            double.TryParse(E_CarLength, out _dCLength);
            double.TryParse(E_CarWidth, out _dCwidth);
            double.TryParse(E_CarHeight, out _dCheight);
            E_CurrentSamplingInfo.En_TotleLength = _dTotalLength;
            E_CurrentSamplingInfo.En_Length = _dCLength;
            E_CurrentSamplingInfo.En_Width = _dCwidth;
            E_CurrentSamplingInfo.En_Height = _dCheight;
            E_CurrentSamplingInfo.En_Postions = txtPostions.Text == "0" ? string.Empty : txtPostions.Text;

            if (DAL.SqlLite.Main.Instance.DoInsertSamplingBegin(E_CurrentSamplingInfo, E_CrrentListSamplingPos, out E_CurrentSamplingIdOfLocal))
            {
                //生成采样标签
                E_CurrentDrawString = string.Format("车牌号：{0}\r\n批次号：{1}\r\n煤种：{2}\r\n物料：{3}\r\n供应商：{4}\r\n采样点数：{5}\r\n布点方式：{6}\r\n缩分间隔：{13}\r\n布点坐标：{7}\r\n车长：{8}m\r\n车厢长：{9}m\r\n车厢宽：{10}m\r\n车厢离地高：{11}\r\n拉筋位置：{12}\r\n光幕遮挡数：{13}\r\n激光测距距离：{14}",
                                                    E_CurrentSamplingInfo.En_Car, E_CurrentSamplingInfo.En_Batch, CacheUser.E_KeyInformation ? E_CurrentSamplingInfo.En_MineName : "", CacheUser.E_KeyInformation ? E_CurrentSamplingInfo.En_MaterielName : "",
                                                    CacheUser.E_KeyInformation ? E_CurrentSamplingInfo.En_SupplierName : "", E_CrrentListSamplingPos.Count, EnumHelper.GetEnumDes(E_CurrentLayoutType), DoGetPosintString(E_CrrentListSamplingPos),
                                                    E_CarTotalLength, E_CarLength, E_CarWidth, E_CarHeight, E_CarPostion, _iSubdivision, E_CurtainCount, E_LaserSpace);

                //保存车头照片
                if (CacheMemoryCenter.E_CaptureHead != null)
                {
                    Image _imgBegin = DoDrawString(CacheMemoryCenter.E_CaptureHead, E_CurrentDrawString, Color.Yellow, 10);
                    MemoryStream memoryStream = new MemoryStream();
                    _imgBegin.Save(memoryStream, ImageFormat.Jpeg);
                    var imgPath = ImageSaver.DoSaveImage(E_CurrentSamplingIdOfLocal, _imgBegin, true);
                    if (DAL.SqlLite.Main.Instance.DoInsertImages(imgPath, true, E_CurrentSamplingIdOfLocal))
                        FormHelper.ApplicationShow(UI.MsgType.Information, "开始采样图片本地保存成功");
                    else
                        FormHelper.ApplicationShow(UI.MsgType.Error, "开始采样图片本地保存出错!详见日志");
                    memoryStream = null;
                }

                FormHelper.ApplicationShow(UI.MsgType.Information, "采样开始数据本地保存成功");

                short[] _CmdPlcs = new short[E_CrrentListSamplingPos.Count * 3 + 14];
                bool _bNeedClear = E_CurrentSamplingInfo.En_Batch != E_SamplingBatchLast;
                if (_bNeedClear)
                    FormHelper.ApplicationShow(UI.MsgType.Error, "采样批次产生变更，当前需要清洗");
                _CmdPlcs[0] = _bNeedClear ? (short)101 : (short)100;//100正常采样 101清洗采样
                _CmdPlcs[1] = (short)E_CurrentSamplingInfo.En_SamplingPosCount;
                _CmdPlcs[2] = (short)E_CurrentSamplingInfo.En_SamplingPail;
                for (int i = 3; i < 14; i++)
                {
                    _CmdPlcs[i] = 0;
                }
                int _iStep = 14;
                foreach (Entity.SamplingPos pos in E_CrrentListSamplingPos)
                {
                    _CmdPlcs[_iStep] = (short)pos.X;
                    _iStep++;
                    _CmdPlcs[_iStep] = (short)pos.Y;
                    _iStep++;
                    _CmdPlcs[_iStep] = (short)pos.Z;
                    _iStep++;
                }

                //测试模式，不采样...
                if (CacheMemoryCenter.E_NoSampling)
                {
                    FormHelper.ApplicationShow(UI.MsgType.Information, $"司机触发采样：测试模式，不采样...");
                    _bCapCaptureCarNo = false;//解除司机按钮防误触锁定
                    return;
                }

                //开始采样
                if (Task.Cyj.Instance.DoWrite(0, _CmdPlcs))
                {
                    FormHelper.ApplicationShow(UI.MsgType.Information, "开始采样命令下达成功");
                    E_CrrentListSamplingPos = null;
                    CacheMemoryCenter.E_SamplingInfo = E_CurrentSamplingInfo;

                    //将采样信息打包,采样完成之后传入封装机使用
                    _bSaveSendDataPacking = false;
                    _modelSave = new Entity.SamplingInfoForPailSave();
                    _modelSave.E_SamplingCarNum = E_CurrentCarNum;
                    _modelSave.E_SamplingIdIfLocal = E_CurrentSamplingIdOfLocal;
                    _modelSave.E_SamplingPail = E_CurrentSamplingInfo.En_SamplingPail;
                    _modelSave.E_SamplingPoscount = E_CurrentSamplingInfo.En_SamplingPosCount;
                    _modelSave.E_SamplingPailCard = string.Empty;
                    _modelSave.E_SamplingBatchCode = E_CurrentSamplingInfo.En_Batch;

                    E_SamplingBatchLast = E_CurrentSamplingInfo.En_Batch;
                    E_CurrentSamplingInfo = null;
                    _bSaveSamplingImage = false;
                    _bSaveSamplingComplete = false;

                    LiveShow.DoClearScreen();
                    CacheMemoryCenter.E_CaptureHead = null;
                    ActionCenter.Action.Instance.DoRefreshSamplingPail();
                    //语音播报
                    Voicer.Instance.DoSendSound("采样开始，请站在安全区域等待");
                }
                else
                {
                    _bCapCaptureCarNo = false;//解除司机按钮防误触锁定
                    FormHelper.ApplicationShow(UI.MsgType.Error, "开始采样命令下达失败!详见日志");
                }
            }
            else
            {
                _bCapCaptureCarNo = false;//解除司机按钮防误触锁定
                FormHelper.ApplicationShow(UI.MsgType.Error, "采样开始数据本地保存失败");
            }

        }


        /// <summary>
        /// 拉筋规避
        /// </summary>
        /// <param name="_strPostions"></param>
        /// <param name="_iCurtainCount"></param>
        /// <param name="_modelInfo"></param>
        /// <param name="_listPos"></param>
        /// <returns></returns>
        private List<Entity.SamplingPos> DoAvoidLacingWire(int _iCurtainCount, Entity.SamplingInfo _modelInfo, List<Entity.SamplingPos> _listPos)
        {
            List<Entity.SamplingPos> _listResult = new List<Entity.SamplingPos>();
            if (!string.IsNullOrEmpty(_modelInfo.En_Postions) && _modelInfo.En_Postions != "0")
            {
                try
                {
                    int _iStep = 0;
                    int _iTieBarPostion;
                    double _dPhysicsPostion;
                    List<string> _listStrPostions = new List<string>();
                    List<Entity.TieBar> _listTieBar = new List<Entity.TieBar>();
                    string[] _arrStrPostions = _modelInfo.En_Postions.Split(',');
                    if (_arrStrPostions.Length > 0)
                    {
                        foreach (string postion in _arrStrPostions)
                        {
                            if (!string.IsNullOrEmpty(postion))
                            {
                                _iStep++;
                                //_dPhysicsPostion = Convert.ToDouble(_modelInfo.En_TotleLength * 1000) - ((E_XGA_Count - _iCurtainCount) * E_XGA_Space) - double.Parse(postion) * 1000 - E_Aoto_XBegin_Space;
                                _dPhysicsPostion = Convert.ToDouble(_modelInfo.En_TotleLength * 1000) - _iCurtainCount * E_XGA_Space - E_Aoto_XBegin_Space - double.Parse(postion) * 1000;
                                _iTieBarPostion = Convert.ToInt32(System.Math.Floor(E_Aoto_XBegin + _dPhysicsPostion / E_Aoto_XPulse));
                                _listTieBar.Add(new Entity.TieBar(_iStep, postion, _iTieBarPostion, E_TieBarProtectionDistance));
                            }
                        }
                    }
                    if (CacheMemoryCenter.E_IsDebug)
                    {
                        foreach (Entity.TieBar et in _listTieBar)
                        {
                            DoShowMsgByOperateType(true, UI.MsgType.Information, string.Format("拉筋:{0} 位置:{1} 坐标:{2} 保护值:{3} 最小:{4} 最大:{5}", et.E_Number, et.E_PhysicsPostion, et.E_CoordinatePostion, et.E_ProtectionValue, et.E_MinValue, et.E_MaxValue));
                        }
                    }

                    //遍历已有采样点规避拉筋
                    if (_listTieBar != null && _listTieBar.Count > 0)
                    {
                        foreach (Entity.SamplingPos spo in _listPos)
                        {
                            foreach (Entity.TieBar et in _listTieBar)
                            {
                                if (spo.X > et.E_MinValue && spo.X < et.E_MaxValue)
                                {
                                    if (CacheMemoryCenter.E_IsDebug)
                                        DoShowMsgByOperateType(true, UI.MsgType.Error, string.Format("块号:{0},大车坐标:{1},处在第:{2}拉筋,规避{3}与{4}之间,系统将自动进行规避", spo.BlockNumber, spo.X, et.E_Number, et.E_MinValue, et.E_MaxValue));
                                    if (spo.X > et.E_CoordinatePostion)
                                        spo.X = et.E_MaxValue;
                                    else
                                        spo.X = et.E_MinValue;
                                    break;
                                }
                            }
                        }
                    }
                    _listResult = _listPos;
                    FormHelper.ApplicationShow(UI.MsgType.Information, "拉筋规避计算完成");
                }
                catch (Exception ex)
                {
                    _listResult = new List<Entity.SamplingPos>();
                    FormHelper.ApplicationShow(UI.MsgType.Error, "拉筋规避计算出现未知异常");
                    Log.LogHelper.DoWriteLogTypeSubitem(Log.LogType.Program, Log.LogSubitem.Forms, "拉筋规避计算出现未知异常");
                    Log.LogHelper.DoWriteLogTypeSubitem(Log.LogType.Program, Log.LogSubitem.Forms, ex.ToString());
                }
            }
            return _listResult;
        }


        /// <summary>
        /// 根据当前操作类型给出提示
        /// </summary>
        /// <param name="isAoto"></param>
        private void DoShowMsgByOperateType(bool isAoto, UI.MsgType type, string msg)
        {
            if (isAoto)
                FormHelper.ApplicationShow(type, msg);
            else
                UI.MsgBox.Show(type, msg);
        }
        #endregion


        #region 手动画框采样
        /// <summary>
        /// 画框完成
        /// </summary>
        /// <param name="Xbegin"></param>
        /// <param name="Ybegin"></param>
        /// <param name="Xend"></param>
        /// <param name="Yend"></param>
        private void LiveShow_DoDrawComplete(int Xbegin, int Ybegin, int Xend, int Yend)
        {
            FormHelper.ApplicationClear();
            decimal _dweight = 0;
            decimal.TryParse(E_CarHeight, out _dweight);
            if (_dweight < (decimal)1.2)
            {
                MessageBox.Show("当前没有车厢距离地面高度，情检查。", Text, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                LiveShow.DoClearScreen();
                return;
            }
            if (string.IsNullOrEmpty(txtCarno.Text))
            {
                MessageBox.Show("当前车辆尚未刷卡，禁止画框。", Text, MessageBoxButtons.OK, MessageBoxIcon.Hand);
                LiveShow.DoClearScreen();
                return;
            }
            FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("像素 XB:{0}  XE:{1} YB:{2} YE:{3}", Xbegin, Xend, Ybegin, Yend));
            //判断当前布点方式
            switch (txtLayoutType.SelectedIndex)
            {
                case 0:
                    E_CurrentLayoutType = SamplingPosMakeType.GB_EquaRand;
                    break;
                case 1:
                    E_CurrentLayoutType = SamplingPosMakeType.GB_FullRand;
                    break;
                default:
                    E_CurrentLayoutType = SamplingPosMakeType.KD_3PartRand;
                    break;
            }

            try
            {

                E_X_Begin = Convert.ToInt32(E_xValue + (double)Xbegin / E_xScale);
                E_X_End = Convert.ToInt32(E_xValue + (double)Xend / E_xScale);
                E_Y_Begin = Convert.ToInt32(E_yValue + (double)Ybegin / E_yScale);
                E_Y_End = Convert.ToInt32(E_yValue + (double)Yend / E_yScale);
                if (CacheMemoryCenter.E_IsDebug)
                    FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("计算1 XB:{0}  XE:{1} YB:{2} YE:{3}", E_X_Begin, E_X_End, E_Y_Begin, E_Y_End));

                if (E_X_Begin > E_X_End)
                {
                    E_X_Begin ^= E_X_End;
                    E_X_End ^= E_X_Begin;
                    E_X_Begin ^= E_X_End;
                }
                if (E_Y_Begin > E_Y_End)
                {
                    E_Y_Begin ^= E_Y_End;
                    E_Y_End ^= E_Y_Begin;
                    E_Y_Begin ^= E_Y_End;
                }
                if (CacheMemoryCenter.E_IsDebug)
                    FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("计算2 XB:{0}  XE:{1} YB:{2} YE:{3}", E_X_Begin, E_X_End, E_Y_Begin, E_Y_End));

                E_X_Begin += E_xProtect;
                E_Y_Begin += E_yProtect;
                E_X_End -= E_xProtect;
                E_Y_End -= E_yProtect;
                if (CacheMemoryCenter.E_IsDebug)
                    FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("保护1 XB:{0}  XE:{1} YB:{2} YE:{3}", E_X_Begin, E_X_End, E_Y_Begin, E_Y_End));

                if (E_X_Begin < E_xMin)
                {
                    E_X_Begin = E_xMin;
                }
                if (E_X_End > E_xMax)
                {
                    E_X_End = E_xMax;
                }
                if (E_Y_Begin < E_yMin)
                {
                    E_Y_Begin = E_yMin;
                }
                if (E_Y_End > E_yMax)
                {
                    E_Y_End = E_yMax;
                }
                if (CacheMemoryCenter.E_IsDebug)
                    FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("终值 XB:{0}  XE:{1} YB:{2} YE:{3}", E_X_Begin, E_X_End, E_Y_Begin, E_Y_End));

                txtX1.Text = Convert.ToString(Xbegin);
                txtX2.Text = Convert.ToString(Xend);
                txtY1.Text = Convert.ToString(Ybegin);
                txtY2.Text = Convert.ToString(Yend);

                Share.SamplingPosGen samplingPosGen = new Share.SamplingPosGen(E_X_Begin, E_X_End, E_Y_Begin, E_Y_End, DoCalculatedHeight(double.Parse(E_CarHeight)), 0, 0);
                //E_CrrentListSamplingPos = samplingPosGen.MakeSamplingPos(E_SamplingPosCount, E_CurrentLayoutType);
                //随机分布采样块 18块均匀随机
                E_CrrentListSamplingPos = Coordinate(E_SamplingPosCount, DoCalculatedHeight(double.Parse(E_CarHeight)));

                //随机分布 采样块
                E_CrrentListSamplingPos = samplingPosGen.ToRandomPos(E_CrrentListSamplingPos);
                 
                if (E_CrrentListSamplingPos != null && E_CrrentListSamplingPos.Count > 0)
                {
                    //渲染布点
                    ActionCenter.Action.Instance.E_SamplingPos = E_CrrentListSamplingPos;
                    int _height = DoCalculatedHeight(double.Parse(E_CarHeight));
                    if (CacheMemoryCenter.E_IsDebug)
                    {
                        Log.LogHelper.DoWriteLogTypeSubitem(Log.LogType.Program, Log.LogSubitem.System, "记录测试坐标------------------------------------------");
                        foreach (Entity.SamplingPos pos in E_CrrentListSamplingPos)
                        {
                            FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("BlockNO:{3} X:{0} Y:{1} Z:{2} ", pos.X, pos.Y, _height, pos.BlockNumber));
                            Log.LogHelper.DoWriteLogTypeSubitem(Log.LogType.Program, Log.LogSubitem.System, string.Format("X:{0} Y:{1} Z:{2} MinX:{3} MaxX:{4} MinY:{5} MaxY:{6}\r\n", pos.X, pos.Y, _height, pos.XBegin, pos.XEnd, pos.YBegin, pos.YEnd));
                        }
                        Log.LogHelper.DoWriteLogTypeSubitem(Log.LogType.Program, Log.LogSubitem.System, "------------------------------------------------------");
                    }
                    _alreadyFrameg = true;

                    /*
                    * 补充采样信息
                    */
                    if (E_CurrentSamplingInfo != null)
                    {
                        E_CurrentSamplingInfo.En_SamplingPosCount = E_SamplingPosCount;
                        E_CurrentSamplingInfo.En_SamplingLayout = Convert.ToInt32(E_CurrentLayoutType);
                    }
                    /*
                     * 保存画框图片
                     */
                    //截图
                    Image _imgDraw = null;
                    LiveShow.DoCatchImage(ref _imgDraw, "", false, false);
                    MemoryStream memoryStream = new MemoryStream();
                    if (_imgDraw == null)
                    {
                        FormHelper.ApplicationShow(UI.MsgType.Error, "抓图失败：无法获取视频截图。");
                        return;
                    }
                    else
                    {
                        var _strDraw = string.Format("时间：{0}\r\n车牌号：{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), txtProvince.Text + txtCarno.Text);
                        _imgDraw = DoDrawString(_imgDraw, _strDraw, Color.Yellow, 20);
                        _imgDraw.Save(memoryStream, ImageFormat.Jpeg);
                        ImageSaver.DoSaveImage(txtProvince.Text + txtCarno.Text, _imgDraw);
                    }
                }
                else
                    DoShowMsgByOperateType(false, UI.MsgType.Waring, "画框生成采样点失败！请仔细检查相关配置参数！");
            }
            catch (Exception ex)
            {
                _alreadyFrameg = false;
                E_CrrentListSamplingPos = null;
                FormHelper.ApplicationShow(UI.MsgType.Error, ex.ToString());
                Log.LogHelper.DoWriteLogTypeSubitem(Log.LogType.Program, Log.LogSubitem.System, "画框生成采样点失败！详情见错误日志！");
                Log.LogHelper.DoWriteLogTypeSubitem(Log.LogType.Program, Log.LogSubitem.System, ex.ToString());
                DoShowMsgByOperateType(false, UI.MsgType.Error, "画框生成采样点失败！详情见错误日志！");
            }
        }

        /// <summary>
        /// 校验参数是否合理
        /// </summary>
        /// <param name="_modelInfo"></param>
        /// <returns></returns>
        private bool DoCheckOutSamplingInfo(bool isAoto, Entity.SamplingInfo _modelInfo)
        {
            string _strMsg = "";
            decimal _dValue = 0;
            if (string.IsNullOrEmpty(_modelInfo.En_Batch))
                _strMsg += "采样批次号不能为空\r\n";
            if (_modelInfo.En_TotleLength <= 0)
                _strMsg += "车辆总长不能为空或者过小\r\n";
            if (_modelInfo.En_Length <= 0)
                _strMsg += "车厢长不能为空或者过小\r\n";
            if (_modelInfo.En_Width <= 0)
                _strMsg += "车厢宽度不能为空或者过小\r\n";
            if (_modelInfo.En_Height <= 0)
                _strMsg += "车厢距离底部高度不能为空或者过小\r\n";
            if (_modelInfo.En_Length >= _modelInfo.En_TotleLength)
                _strMsg += "车厢长度不能大于整车长度\r\n";

            //将全部分隔符 转换为 英文逗号
            _modelInfo.En_Postions = _modelInfo.En_Postions.ToDouHaoSplitEx();
            if (!string.IsNullOrEmpty(_modelInfo.En_Postions))
            {
                if (_modelInfo.En_Postions != "0")
                {
                    string[] _arr = _modelInfo.En_Postions.ToSplitArrayEx(',').ToArray();
                    foreach (string value in _arr)
                    {
                        decimal.TryParse(value, out _dValue);
                        if (_dValue <= 0)
                        {
                            _strMsg += string.Format("车辆拉筋输入参数不合规,[{0}]\r\n", value);
                            break;
                        }
                    }
                }
            }
            DoShowMsgByOperateType(isAoto, UI.MsgType.Waring, _strMsg);
            return string.IsNullOrEmpty(_strMsg);
        }

        /// <summary>
        /// 计算当前车辆采样深度 厘米转换脉冲
        /// </summary>
        /// <param name="_iCarHeight"></param>
        /// <returns></returns>
        private int DoCalculatedHeight(double _iCarHeight)
        {
            //double _deepScale = ((double)5090 - (double)1392) / ((double)146 - (double)100);
            //if (CacheMemoryCenter.E_IsDebug)
            //    FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("脉冲系数:{0}", _deepScale));
            //double _deep = 146 - (_iCarHeight * 1000 - 1392 + 50) / _deepScale;
            //if (CacheMemoryCenter.E_IsDebug)
            //    FormHelper.ApplicationShow(UI.MsgType.Information, string.Format("计算深度脉冲:{0}", _deep));
            //return Convert.ToInt32(Math.Floor(_deep));
            double _deep = E_zMax - (_iCarHeight * 1000 - E_zValue + 50) / E_zScale;
            return Convert.ToInt32(Math.Floor(_deep));
        }



        #endregion
    }
}
